C++循环案例

目录

1.while循环练习案例:==猜数字==

2.练习案例:水仙花数

3.练习案例:敲桌子

4.练习案例:乘法口诀表


1.while循环练习案例:==猜数字==

案例描述:系统随机生成一个1到100之间的数字,玩家进行猜测,如果猜错,提示玩家数字过大或过小,如果猜对恭喜玩家胜利,并且退出游戏。

#include <iostream>
//time系统时间头文件包含
#include <ctime>
using namespace std;

int main() {
	//添加随机数种子  利用当前系统时间生成随机数,防止每次随机数都一样
	srand((unsigned int)time(NULL));
	//1.系统生成随机数
	int num=rand()%100+1;  // rand()%100 生成0+1~99+1的随机数
	cout<<num<<endl;
	
	//2.玩家进行猜测
	int val=0;
	while(1){
		cin>>val;
		//3.判断玩家的猜测
		if(val>num){
			//猜错  提示猜的结果 过大或者过小 重新返回第2步
			cout<<"猜测过大"<<endl;
		}else if(val<num){
			//猜错  提示猜的结果 过大或者过小 重新返回第2步
			cout<<"猜测过小"<<endl;
		}else{
			//猜对  退出游戏
			cout<<"恭喜您猜对啦"<<endl;
			break;
		}
	}	
	system("pause");
 
	return 0;
}

2.练习案例:水仙花数

案例描述:水仙花数是指一个 3 位数,它的每个位上的数字的 3次幂之和等于它本身

例如:1^3 + 5^3+ 3^3 = 153

请利用do...while语句,求出所有3位数中的水仙花数

#include <iostream>
using namespace std;
 
int main() {
	int num=100;
	int a=0; //百位上的数字
	int b=0; //十位上的数字
	int c=0; //个位上的数字
	int res=0;
	do{
		a=num/100; //百位上的数字
		b=num%100/10; //十位上的数字
		c=num%10; //个位上的数字
		res=a*a*a+b*b*b+c*c*c;
		if(res==num){
			cout<<num<<endl;
		}
		num++;
	}while(num<1000);
 
	system("pause");
 
	return 0;
}

3.练习案例:敲桌子

案例描述:从1开始数到数字100, 如果数字个位含有7,或者数字十位含有7,或者该数字是7的倍数,我们打印敲桌子,其余数字直接打印输出。

#include <iostream>
using namespace std;
 
int main() {
	for(int i=1;i<=100;i++){
		if(i/10==7||i%10==7||i%7==0){
			cout<<"敲桌子"<<endl;
		}else{
			cout<<i<<endl;
		}
	}
 
	system("pause");
 
	return 0;
}

4.练习案例:乘法口诀表

案例描述:利用嵌套循环,实现九九乘法表

#include <iostream>
using namespace std;
 
int main() {
	for(int i=1;i<10;i++){
		for(int j=1;j<=i;j++){
			cout<<j<<"*"<<i<<"="<<j*i<<" ";
		}
		cout<<endl;
	}
	system("pause");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

摸鱼特长生.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值