选择结构
单行 if:
int age = 10;
if (age < 18)
{
cout << "未成年,请在家长的陪同下观看!" << endl;
}
多行 if:
int age = 10;
if (age < 18)
{
cout << "未成年,请在家长的陪同下观看!" << endl;
}
else
{
cout << "点击播放" << endl;
}
多条件 if:
int age = 0;
cout << "请输入年龄:" << endl;
cin >> age;
if (age < 18 && age > 0)
{
cout << "未成年" << endl;
}
else if(age >= 18 && age < 35)
{
cout << "年轻人" << endl;
}
else if (age >= 35 && age < 50)
{
cout << "中年人" << endl;
}
else if (age >= 50 && age < 120)
{
cout << "老年人" << endl;
}
else
{
cout << "不是人" << endl;
}
嵌套 if:
int a = 100;
int b = 200;
// 如果条件为真,则进入判断
if (a == 100)
{
// 如果条件为真,则输出下面的语句
if (b == 200)
{
cout << "a 的值是 100,且 b 的值是 200" << endl;
}
}
三目运算符:
int a = 10;
int b = 20;
int c = 0;
c = a > b ? a : b;
// 20
cout << c << endl;
switch 判断语句:
char level = NULL;
cout << "请输入等级:" << endl;
cin >> level;
switch (level)
{
case 'D':
cout << "等级D" << endl;
break;
case 'C':
cout << "等级C" << endl;
break;
case 'B':
cout << "等级B" << endl;
break;
case 'A':
cout << "等级A" << endl;
break;
case 'S':
cout << "等级S" << endl;
break;
// default:在case 都不匹配时执行
default:
cout << "无等级" << endl;
}
while 循环:
int a = 10;
while (a < 16)
{
cout << "a = " << a << endl;
a++;
}
do while 循环:输出所有的“水仙花数
水仙花数:一个三位数其各位数字的立方和等于该数本身,例如153是“水仙花数”,因为:153 = 1^3 + 5^3 + 3^3
#include<iostream>
using namespace std;
#include<cmath>
int main()
{
int num = 100;
do
{
int a = pow(num % 10, 3); //num对10取余拿到num的个位数
int b = pow(num / 10 % 10, 3);//num除10再对10取余拿到num的十位数
int c = pow(num / 100, 3);//num除100拿到num的百位数
if (a + b + c == num)
{
cout << num << endl;
}
num++;
} while (num < 1000);
system("pause");
return 0;
}
运行结果:153 370 371 407
for 循环
敲桌子:在一个1-100循环报数中,当数字是7的倍数或个位是7或十位是7,输出敲桌子来替代数字原有的值输出
#include<iostream>
using namespace std;
int main()
{
for (int a = 1;a<=100;a++)
{
if (a % 7 == 0 || a % 10 == 7 || a / 10 == 7) {
cout << a << "敲桌子" << endl;
}
}
system("pause");
return 0;
}
嵌套循环
乘法口诀表:
#include<iostream>
using namespace std;
int main()
{
//九九乘法表
for (int i = 1;i<10;i++)
{
for (int j = 1; j <= i; j++)
{
cout << j << "*" << i <<"="<< i * j << " ";
}
cout << "\n";
}
system("pause");
return 0;
}
break和continue的区别
break退出整个循环,
continue退出本次循环,执行下一次循环