28.程序流程結(jié)構(gòu)——循環(huán)結(jié)構(gòu)——while
while(循環(huán)結(jié)束條件){需要循環(huán)執(zhí)行的語(yǔ)句}? ?//注意欠气,避免死循環(huán)
demo:猜數(shù)字
代碼:
int main() {
//系統(tǒng)生成隨機(jī)數(shù)
? int num = rand()%100 +1; //生成1~100的隨機(jī)數(shù)
? std::cout<<"系統(tǒng)已經(jīng)生成隨機(jī)數(shù)"<<std::endl;
? //玩家猜測(cè)
? int val =0;
//循環(huán)體
? while (1){
std::cout<<"請(qǐng)輸入猜測(cè)的數(shù)字:"<<std::endl;
? ? ? std::cin>>val;
? ? ? //提示玩家
? ? ? if (val >num){
std::cout<<"猜測(cè)過(guò)大"<<std::endl;
? ? ? }else if (val < num){
std::cout<<"猜測(cè)過(guò)小"<<std::endl;
? ? ? }else{
std::cout<<"恭喜您猜對(duì)了"<<std::endl;
break;
? ? ? }
}
}
運(yùn)行結(jié)果:
系統(tǒng)已經(jīng)生成隨機(jī)數(shù)
請(qǐng)輸入猜測(cè)的數(shù)字:
50
猜測(cè)過(guò)大
請(qǐng)輸入猜測(cè)的數(shù)字:
42
恭喜您猜對(duì)了
注意拙吉,此處生成的隨機(jī)數(shù)為偽隨機(jī),多次運(yùn)行后即可發(fā)現(xiàn)每次生成的數(shù)都是42凛虽。
如何使偽隨機(jī)數(shù)變成真正的隨機(jī)數(shù)蚁趁?
1.引入頭文件?
#include <ctime>
2.添加隨機(jī)數(shù)種子 作用:利用當(dāng)前系統(tǒng)的時(shí)間生成隨機(jī)數(shù)据途,防止每次隨機(jī)數(shù)都一樣
srand((unsigned int)time(NULL));
28.程序流程結(jié)構(gòu)——循環(huán)結(jié)構(gòu)——do...while循環(huán)
do{要循環(huán)執(zhí)行的語(yǔ)句}while(循環(huán)結(jié)束條件)
do...while和while的區(qū)別:
do...while會(huì)先執(zhí)行一次循環(huán)語(yǔ)句
demo:水仙花數(shù)
水仙花數(shù)是指一個(gè)三位數(shù),其每一位上的數(shù)字的三次冪之和等于它本身
利用do...while語(yǔ)句朱巨,求出所有三位數(shù)中的水仙花數(shù)史翘。
代碼:
int main() {
//所有三位數(shù):100~999
? //百位數(shù):數(shù)字/100 十位數(shù):(數(shù)字%100)/10 個(gè)位數(shù):(數(shù)字%100)%10
? //判斷:個(gè)位數(shù)三次方+十位數(shù)三次方+百位數(shù)三次方 = 數(shù)字本身,輸出
? int num =100;
? int a =0;//百位數(shù)
? int b =0;//十位數(shù)
? int c =0;//個(gè)位數(shù)
? ? do {
a = num/100;
? ? ? ? b = (num%100)/10;
? ? ? ? c = (num%100)%10;
? ? ? ? if (a*a*a + b*b*b + c*c*c == num)
std::cout<<num<<"是水仙花數(shù)"<<std::endl;
? ? ? ? num++;
? ? }
while (num <1000);
}
運(yùn)行結(jié)果:
153是水仙花數(shù)
370是水仙花數(shù)
371是水仙花數(shù)
407是水仙花數(shù)
29.程序流程結(jié)構(gòu)——循環(huán)結(jié)構(gòu)——for循環(huán)
格式:? for(起始表達(dá)式;條件表達(dá)式;末尾循環(huán)體){循環(huán)語(yǔ)句}
for循環(huán)本質(zhì)上和while冀续、do...while類似琼讽,只是結(jié)構(gòu)更為清晰代碼量更少
demo:敲桌子
從1數(shù)到100.如果數(shù)字個(gè)位含有7,或者10位含有7沥阳,或者該數(shù)字是7的倍數(shù)跨琳,我們打印敲桌子,其余數(shù)字直接打印輸出桐罕。
代碼:
int main() {
int a =0;//個(gè)位
? ? int b =0;//十位
? ? for (int i =1; i <101; i++) {
a = i%10;
? ? ? ? b = i/10;
? ? ? ? if (a ==7 || b ==7 || i%7 ==0){
std::cout<<"敲桌子"<<std::endl;
? ? ? ? }else
? ? ? ? ? ? std::cout<<i<<std::endl;
? ? }
}
運(yùn)行結(jié)果:
1
2
3
4
5
6
敲桌子
8
9
10
11
12
13
敲桌子
15
16
敲桌子
18
19
20
敲桌子
22
23
24
25
26
敲桌子
敲桌子
29
30
31
32
33
34
敲桌子
36
敲桌子
38
39
40
41
敲桌子
43
44
45
46
敲桌子
48
敲桌子
50
51
52
53
54
55
敲桌子
敲桌子
58
59
60
61
62
敲桌子
64
65
66
敲桌子
68
69
敲桌子
敲桌子
敲桌子
敲桌子
敲桌子
敲桌子
敲桌子
敲桌子
敲桌子
敲桌子
80
81
82
83
敲桌子
85
86
敲桌子
88
89
90
敲桌子
92
93
94
95
96
敲桌子
敲桌子
99
100