while语句
语法:while(循环条件){循环语句}
只要循环条件为真就会执行循环语句,直到不为真时退出循环
#include <iostream>
#include<iomanip>
using namespace std;
int main() {
//在控制台打印0-9
int i = 0;
while (i < 10) {
cout << i++ << endl;
}
return 0;
}
使用while时要注意循环条件,不要造成死循环
练习题:猜数字
#include <iostream>
#include<iomanip>
#include<ctime>
using namespace std;
int main() {
//添加随机数种子,使每次运行程序产生不同的随机数
srand((unsigned int)time(NULL));
int num = rand() % 100 + 1, val;
while (1) {
cout << "请输入你要猜的数字(1-100)" << endl;
cin >> val;
if (val > num) {
cout << "你猜的数字大了" << endl;
}
else if (val < num) {
cout << "你猜的数字小了" << endl;
}
else {
cout << "恭喜你,猜对了" << endl;
break;
}
}
return 0;
}
do-while语句
语法:do{循环语句}while(循环条件)
与while的区别:do-while会先执行一次循环语句,再判断循环条件的真假执行下一次循环,while是先判断循环条件再决定是否执行循环语句.
#include <iostream>
using namespace std;
int main() {
int i = 0;
do
{
cout << i++ << endl;
} while (i < 10);
return 0;
}
for循环语句
语法:for(起始表达式;条件表达式;末尾循环体) {循环语句;}
#include <iostream>
#include<iomanip>
#include<cmath>
using namespace std;
int main() {
for (int i = 0; i < 10; i++)
{
cout << i << endl;
}
return 0;
}