我正在寫這個程序,它會猜測用戶正在考慮的數字。經過幾天的工作,我無法弄清楚它出了什麼問題。 另外我提出的分配等級並不是我的預期。 請幫忙。爲什麼100不包括在這個程序中?
- 用戶可以猜100,但我的程序使用中點規則,所以只能達到99.我怎樣才能使100包含?
- 如果我一直按'l'程序將最終打破循環並打印如果你想再試一次?
- 有沒有更好的方法來編寫這個程序?請舉例。
下面是實際的程序:
寫一個程序中,可以計算出由人類用戶選擇的號碼。用戶會想到一個介於1到100之間的數字。該程序將進行猜測,用戶會告訴程序猜測更高或更低。程序應該找到兩個數字的中點,並詢問數字是高還是低。
#include <iostream>
using namespace std;
int main() {
char check;
char tryagain;
do {
int midpoint;
const int MAX = 100;
const int MIN = 1;
int y = MAX;
int x = MIN;
cout << "Think of a number between 1 and 100." << endl;
midpoint = (x + y)/2;
while (x != y || y != x) {
cout << endl << "Is it" << " " << midpoint << " " << "?";
cin >> check;
if (check == 'l' || check == 'L') {
y = midpoint;
midpoint = (x + y)/2;
}
else if (check == 'h' || check == 'H') {
x = midpoint;
midpoint = (x + y)/2;
}
else if (check == 'c' || check == 'C') {
break;
}
else {
cout << "Incorrect choice." << endl;
}
}
cout << "Great! Do you want to try again? (y/n)";
cout << endl;
cin >> tryagain;
} while (tryagain == 'y' || tryagain != 'n');
return 0;
}
'X = Y || y!= x' ?! – Biffen
你能澄清嗎?什麼線路不能像你期望的那樣工作?在第1點中,你提到它不是100包含,但是實際問題是什麼? – TankorSmash
假設您從1到100的可能範圍開始,並且用戶說這個數字大於50.那麼您的新範圍不應該是50到100,而是51到100. –