例子
小猪体重的比较(if else语句)
int main21()
{
int a;
int b;
int c;
cout << "请输入小猪a的体重\n"<<endl;
cin >> a;
cout << "请输入小猪b的体重\n"<< endl;
cin >> b;
cout << "请输入小猪c的体重\n"<< endl;
cin >> c;
cout << "小猪a的体重为" << a << endl;
cout << "小猪b的体重为" << b << endl;
cout << "小猪c的体重为" << c << endl;
if (a > b)
{
if (a > c)
{
cout << "最重的小猪为a" << endl;
}
else cout << "最重的小猪为c" << endl;
}
else
{
if (b > c)
{
cout << "最重的小猪为b" << endl;
}
else cout << "最重的小猪为c" << endl;
}
system("pause");
return 0;
}
水仙花数
do while 循环案例
案例描述:水仙花数是指一个三位数,他的每个位上的数字的三次幂之和等于他本身
利用do while 循环求出所有水仙花数
例如13 +53 +33 =153。
获取个位189%=9;
获取十位189/10=15(C++中自动舍去小数);15%10=5。
int main()
{
int a=100;
do
{
int b = a%10;
int c = a / 10 % 10;
int d = a / 100;
if (b*b*b+c*c*c+d*d*d==a)
{
cout << a << endl;
}
a++;
} while (a < 1000);
system("pause");
return 0;
}
敲桌子(逢7过)
案例描述;从1开始数到数字100,如果数字各位含有7,或者是7的倍数,打印敲桌子,其余数字直接打印输出。
int main()
{
for (int a=1; a<100 ; a++)
{
if (a % 7 == 0)
{
cout << "敲桌子" << endl;
}
else if (a % 10 == 7)
{
cout << "敲桌子" << endl;
}
else cout << a << endl;
//更简单的写法
/*
for (int a=1; a<100 ; a++)
{
if (a % 7 == 0||a % 10 == 7)
{
cout << "敲桌子" << endl;
}
else cout << a << endl;
*/
}
system("pause");
return 0;
}
乘法口诀表
int main()
{
//i为行数,j为列数,当列数小于等于行数时输出
for (int i = 1; i < 10;i++)
{
for (int j = 1; j <= i; j++)
{
cout << i << "*" << j << "=" << i * j<<" ";
}cout << endl;
}
system("pause");
return 0;
}