C++入门day03-1

[感触:学Python有一种轻飘飘的感觉,学C/C++时才知道自己的数学知识是多么匮乏,才想起编程其实最初是用来计算的]
[案例:水仙花数,敲桌子,乘法口诀表]

do…while

do{循环语句}while(循环条件)

与while的区别:do…while…会先执行一次循环语句,再判断条件

练习案例:水仙花数
案例描述:水仙花数是指一个3位数,它的每个位上的数字的3次幂之和等于它本身,
例如:1^3+5^3+3^3=153
请利用 do...while 语句,求出所有3位数中的水仙花数

思路:

1、所有三位数(100~999)
2、获取个位:153%10 = 3  对数字取模于10,可以获取到个位  153%10 = 3
   获取十位:153/10 = 15, 15%10 = 5  先整除于10,得到两位数,再取模于10,得到十位
   获取百位:153/100 = 1  直接整除于100,获取百位

水仙花数

#include <iostream> 
using namespace std;

// do...while,水仙花数 
int main()
{
	int num = 100;
	do
	{
		int unit = 0;
		int decade = 0;
		int hundred = 0;
		
		unit = num % 10;
		decade = num / 10 % 10;
		hundred = num / 100;
		
		if (unit*unit*unit+decade*decade*decade+hundred*hundred*hundred == num)
		{
			cout<<num<<endl;
		}
		num++;
	}while(num<1000);
	
	
	system("pause");
	return 0;
}

运行结果:

153
370
371
407
请按任意键继续. . .

for 循环

for (起始表达式;条件表达式;末尾循环体) {循环语句}

练习案例:敲桌子

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

思路:

  1. 先输出1到100这些数字
  2. 从这100个数字中找到特殊数字,改为“敲桌子”

特殊数字

  • 7的倍数 (7,14,21,28…) % 7 = 0
  • 个位有7 (7,17,27,37…) % 10 = 7
  • 十位有7 (70,71,72,73…) / 10 = 7
#include <iostream> 
using namespace std;

// for...敲桌子游戏 
int main()
{
	// 1、先输出 1~100 数字
	for(int i=1;i<=100;i++)
	{
		// 2、从100个数字中找到特殊数字 
		if(i%7==0||i%10==7||i/10==7)
		{
			cout<<"敲桌子"<<endl;
		}
		else
		{
			cout<<i<<endl;
		}
	}

	system("pause");
	return 0;
}

嵌套循环

  • 案例:打印出 10*10 的星图

外层执行一次,内层执行一周
约定俗成:外层 i , 内层 j

#include <iostream> 
using namespace std;

// 嵌套循环...星图 
int main()
{
	for(int i=0;i<10;i++)
	{
		for(int j=0;j<10;j++)
		{
			cout<<"* ";
		}
		cout<<endl;
	}


	system("pause");
	return 0;
}

案例:乘法口诀表

列数 * 行数 = 计算结果

#include <iostream> 
using namespace std;

// 嵌套循环...乘法口诀表 
int main()
{
	// 1 打印行数 
	for(int i=1;i<=9;i++)
	{
		// cout<<i<<endl;
		// 2 打印列数
		for(int j=1;j<=i;j++)
		{
			// cout<<j;
			cout<<j<<"*"<<i<<"="<<i*j<<"\t";
		}cout<<endl;
	}

	system("pause");
	return 0;
}

跳转语句

break / continue / goto

goto 可以无条件跳转到某条语句 (因为太强大,所有很少用)

#include <iostream> 
using namespace std;

// do...while 和 for , 以及 goto 
int main()
{
	// do...while
	int num = 0;
	do
	{
		cout<<num<<"  ";
		num++;
	}
	while(num<10);
	cout<<"\n"<<endl;
	// for
	for (int i=0; i<10;i++)
	{
		cout<<i<<"  ";
	}cout<<endl;
	
	// goto
	cout<<"1.xxx"<<endl;
	goto FLAG;
	cout<<"2.xxx"<<endl;
	cout<<"3.xxx"<<endl;
	cout<<"4.xxx"<<endl;
	FLAG:
	cout<<"5.xxx"<<endl;
	
	
	system("pause");
	return 0;
}

运行结果:

0  1  2  3  4  5  6  7  8  9

0  1  2  3  4  5  6  7  8  9
1.xxx
5.xxx
请按任意键继续. . .
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值