c++基础:循环练习案例展示

1.猜数字

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

#include<iostream>
using namespace std;
//time系统时间头文件包含
#include <ctime>
int main()
{
	//添加随机数种子,利用当前系统时间生成随机数,防止每次随机数一样
	srand((unsigned int)time(NULL));
		//1.系统生成随机数
		int num = rand() % 100 + 1; //生成0-99的随机数
	   // cout <<num << endl;
		//2.玩家进行猜测
		int val = 0;
	while (1)
	{
		cin >> val;
		//3.判断玩家的猜测
		if (val > num)
			cout << "猜测过大" << endl;
		else if (val < num)
			cout << "猜测过小" << endl;
		else
		{
			cout << "猜对了" << endl;
			break;//循环中可以利用该关键字推出当前循环
		}
	}
	system("pause");
	return 0;
}

结果:
在这里插入图片描述

2.水仙花数

题目
水仙花数是指一个3位数,它的每个位上的数字的3次幂之和等于它本身。
例如:1^ 3 + 3^ 3+5^3 = 135
代码

#include<iostream>
using namespace std;

int main()
{
	int num = 100;
	do {
		int a = num / 100;
		int b = (num / 10) % 10;
		int c = num % 10;
		if (a * a * a + b * b * b + c * c * c == 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 << "敲桌子" << "\t";
		else
			cout << i << "\t";
	}
	system("pause");
	return 0;

}

结果:
在这里插入图片描述

4.乘法口诀表

问题:
打印输出99乘法口诀表
代码:

#include<iostream>
using namespace std;

int main()
{
	for (int i = 1; i <= 9; i++)
	{
		for (int j = 1; j <= i; j++)
		{
			cout << j << "*" << i << "=" << i * j << "\t";
		}
		cout << endl;
	}
	system("pause");
	return 0;

}

结果:

在这里插入图片描述

  • 4
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值