#include <iostream>
using namespace std;
int main(){
// while(condition){
// 循环体
// }
int i = 0;
while (i < 5){
cout<< "hello" <<endl;
i++;
}
// 求解 1 ~100累加和
int j = 1;
int sum = 0;
while (j <=100){
// sum = sum + j;
sum += j;
cout<< j << " ";
j++;
}
// 换行
cout <<endl;
cout<< "sum = " << sum << endl;
}
求奇数和
#include <iostream>
using namespace std;
int main(){
// 求解 1 ~100奇数累加和
int j = 1;
int sum = 0;
while (j <=100){
sum += j;
cout<< j << " ";
j+=2;
}
// 换行
cout <<endl;
cout<< "sum = " << sum << endl;
}
break 和 cotinue
都是可以中断循环的
- break 跳出本层循环;
- continue跳出本次循环执行下一次循环;
do while循环
不常用
语法:
do{循环语句} while(循环条件)
与while的区别 :do while循环会先执行一次循环, 再去判断循环条件
#include <iostream>
using namespace std;
int main(){
// int i = 1;
// while (i < 1){
// cout<< "sum = "<< endl;
// }
// do{
// cout<< "sum "<< endl;
// }while (i < 1);
// do while 求 1 ~ 100 之间的累加和
int i = 0;
int sum = 0;
do{
i += 1;
sum += i;
}while(i <= 99);
cout << "sum = " << sum << endl;
}
#include <iostream>
using namespace std;
int main(){
//案例描述:系统随机⽣成⼀个1到100之间的数字,玩家进⾏猜测,
// 如果猜错,提⽰玩家数字过⼤或过 ⼩,如果猜对恭喜玩家胜利,并且退出游戏。
int generate_number = 40;
int guess_number;
while (true){
cout << "please input you guess_number " << endl;
cin >> guess_number;
if (guess_number > generate_number){
cout << "too large " << endl;
}else if (guess_number < generate_number){
cout << "too small " << endl;
}else{
cout << "very good " << endl;
break;
}
}
}
电脑生成随机数
int main(){
srand((unsigned int )time(NULL));
int i = 0;
while (i < 100){
// rand()%n 生成 [0, n) 之间的随机整数
// rand()%n + m 生成 [m, m+n) 之间的随机整数
int num = rand()%100 + 1;
cout << "num ="<< num << endl;
if (num==101){
cout << "++++++++++++++++++++++++++++++++++"<< num << endl;
}
i++;
}
}
#include <iostream>
#include <ctime>
using namespace std;
int main(){
//随机种子
srand((unsigned int )time(NULL));
//案例描述:系统随机⽣成⼀个1到100之间的数字,玩家进⾏猜测,
// 如果猜错,提⽰玩家数字过⼤或过 ⼩,如果猜对恭喜玩家胜利,并且退出游戏。
int generate_number;
int guess_number;
// [40, 100]
// generate_number = rand()%61 + 40;
generate_number = rand()%100 + 1; //随机生成 1 ~100 之间的整数
// cout << "generate_number = " << generate_number << endl;
while (true){
cout << "please input you guess_number " << endl;
cin >> guess_number;
if (guess_number > generate_number){
cout << "too large " << endl;
}else if (guess_number < generate_number){
cout << "too small " << endl;
}else{
cout << "very good " << endl;
break;
}
}}
for 循环(最常用)
语法
// for 和 while 可以互相转化
for (初始表达式; 条件表达式; 步进表达式) {
循环体
}
int main() {
for (int i = 0; i < 5; i++) {
cout << "++++++++++++++++++++++++++++++++++" << i << endl;
}
int sum = 0;
// for 求 1 ~ 100 之间的累加和
for (int i = 1; i <= 100; ++i) {
sum += i;
}
cout << "sum = " << sum << endl;
}
网友评论