C++ 入門指南 4.01
練習 30.4 參考程式 - 練習發展猜數字遊戲計算核心
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main(void) {
// 宣告隨機答案變數
srand(time(NULL));
int answer = rand() % 10;
// 宣告猜測變數
int guess;
// 宣告紀錄猜測次數的變數
int count = 0;
// 遊戲互動模式
while (true) {
count += 1;
cout << "請輸入猜測數字:";
cin >> guess;
if (guess == answer) {
cout << "恭喜猜對" << endl;
cout << "一共猜了" << count << "次" << endl;
break;
}
else {
cout << "猜錯~~" << endl;
}
cout << endl;
}
return 0;
}
/* 《程式語言教學誌》的範例程式
http://kaiching.org/
檔名:guess_demo04.cpp
編譯:g++ guess_demo04.cpp
執行:./a.out
功能:猜數字遊戲核心的發展中版本
作者:張凱慶 */
回到練習題目