# 請問怎麼做這一道題目 關於c++

• pick a secret number from 1 to 100

• have someone try to guess the number

• tell them if their guess is too high or too low or correct

• continue asking them to guess until they are correct

<像終極密碼>

• allow the player to change the range of numbers from which to guess from (e.g. allow

for a secret number between –10 and 5)

• keep track of how many tries it takes the player to guess the secret number

• allow the player to replay the game many times, with a different secret number each time

• keep track of how many games the player has played, and what their average number of

guesses per game is

• allow the player to make mistakes in their input (i.e. prevent the program from crashing)

### 1 個解答

• 最佳解答

#include <iostream>

#include <numeric>

#include <vector>

#include <ctime>

using namespace std;

int main()

{

vector<unsigned int> vTries;

while (1)

{

cout << "這是你第" << vTries.size() + 1 << "次玩" << endl;

srand(time(NULL));

int nAns = rand() % 100 + 1;

int nGuess = 0, nCount = 0;

while (nGuess != nAns)

{

cout << "1-100 猜一數字: ";

cin >> nGuess;

nCount++;

if (nGuess < 1 || 100 < nGuess)

{

cout << "輸入錯誤!" << endl;

nCount--;

}

else if (nGuess < nAns)

cout << "你猜的數字小於謎底數字" << endl;

else if (nGuess > nAns)

cout << "你猜的數字大於謎底數字" << endl;

else

{

cout << "猜對了" << endl;

vTries.push_back(nCount);

}

}

char cExit;

cout << "要再玩嗎(y/n) ? ";

cin >> cExit;

if (cExit != 'y' && cExit != 'Y')

{

float nPlayTimes = vTries.size();

cout << "你一共玩 " << nPlayTimes << " 次" << endl;

cout << "平均每次猜 " << (float)accumulate(vTries.begin(), vTries.end(), NULL)/nPlayTimes << "次\n";

break;

}

}

system("pause");

return 0;

}

這個功能

• allow the player to change the range of numbers from which to guess from (e.g. allow for a secret number between –10 and 5)

留給你自己改 (￣▽￣＃)﹏﹏