三目运算符
// 表达式1? 表达式2:表达式3 // 如果表达式1为真 执行表达式 2 并且返回表达式2 的结果 // 如果表达式1为假 执行表达式 3 并且返回表达式3 的结果
#include <iostream>
using namespace std;
int main(){
int a = 100;
int b = 200;
int c = 300;
int max;
cout <<( a > b ? a : b)<<endl;
( a > b ? a : b) = 1000;
cout <<"a = "<< a<<endl;
cout <<"b = "<< b<<endl;
cout <<"san = "<<((a>b?a:b) > c ? (a>b?a:b) : c)<<endl;
}
switch语句
语法
switch(表达式){
case 结果1: 执行语句;
break;
case 结果2: 执行语句;
break;
case 结果3: 执行语句;
break;
...
default: 执行语句;
break;
}
#include <iostream>
using namespace std;
int main(){
cout<< "please input your selection" << endl;
cout<< "1 . run" << endl;
cout<< "2 . taxi" << endl;
cout<< "3 . train" << endl;
cout<< "4 . plane" << endl;
cout<< "5 . sheep" << endl;
cout<< "default foot" << endl;
int num;
cin >> num;
switch (num) {
case 1:
cout<< " run .... " << endl;
break;
case 2:
cout<< " taxi .... " << endl;
break;
case 3:
cout<< " train .... " << endl;
break;
case 4:
cout<< " plane .... " << endl;
break;
case 5:
cout<< " sheep .... " << endl;
break;
default:
cout<< " foot .... " << endl;
break;
}
}
注意1:switch语句中表达式类型只能是整型或者字符型 注意2:case里如果没有break,那么程序会一直向下执行 总结:与if语句比,对于多条件判断时,switch的结构清晰,执行效率高,缺点是switch不可以判断区间
循环结构
while循环
语法
while(循环条件){
循环语句
}
举个例子
#include <iostream>
using namespace std;
int main(){
int i = 1;
int sum = 0;
while (i <= 100){
sum += i;
i++;
}
cout<< "sum = "<< sum << endl;
}
do while循环
语法:
do{循环语句} while(循环条件)
与while的区别 :do while循环会先执行一次循环, 再去判断循环条件
#include <iostream>
using namespace std;
int main(){
int i = 1;
int sum = 0;
while (i <= 100){
sum += i;
i++;
}
cout<< "sum = "<< sum << endl;
}
#include <iostream>
using namespace std;
int main(){
int i = 1;
int sum = 0;
do {
sum +=i;
i++;
} while (i<1);
cout<< "sum = "<< sum << endl;
}
#include <iostream>
using namespace std;
int main(){
srand((unsigned int ) time(NULL));
int generate_number = rand()%100 + 1;
cout<< generate_number<< endl;
int guess_number;
while (true){
cout<< "请输入您要猜的数字 "<< endl;
cin >> guess_number;
if (guess_number > generate_number)
cout<< "猜大了 "<< endl;
else if (guess_number < generate_number)
cout<< "猜小了 "<< endl;
else{
cout<< "恭喜你猜对了 "<< endl;
break;
}
}
}
|