猜數字(加入是否繼續的問句)
by 謝忠佑
2014-12-29 10:20:18, Reply(0), Views(478)

#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
int n,a,max,min;
srand(time(NULL));
char ask='y'; //一開始要設定1個初始值 'y' 表示要繼續玩
while (ask == 'y') { //加入while迴圈,判斷使用者是否要要繼續玩遊戲?
min=1; //要記得將所有變數 歸零(設定成 初始值)
max=100;
ask='y';
a=(rand() % 100) +1;
do {
cout<<"請輸入一個"<<min<<"到"<<max<<"以內的數字猜猜看:"<<endl;
cin>>n;
if(a<n){
cout<<"太大了,再小一點!"<<endl;
if (max > n)
max = n;
}
else if(a>n) {
cout<<"太小了,再大一點!"<<endl;
if (min < n)
min = n;
}
else
cout<<"恭喜答對了!"<<endl;
} while ( a != n );
if (ask=='y' && a==n) { //當玩家繼續玩時且已猜到數字時,才詢問是否要繼續
cout << "是否要繼續新的遊戲(y/n)?";
cin >> ask;
if (ask == 'n') //當玩家不玩時,顯示 再見 的訊息。
cout << "歡迎再度光臨! Bye! Bye!\n";
}
}
system("PAUSE");
return EXIT_SUCCESS;
}