好的,首先,我是计算机科学类(class)的完全初学者。我可以问我的老师,但我没有时间这样做。因此,请期待一些我看不到的非常愚蠢的错误,而我正在使用 eclipse。
这是我的代码:
#include <iostream>
using namespace std;
int something()
{
int big = 1000;//largest number is 1000
int small = 1;//smallest number is 1
//so, best guess is to go in the middle
int c;//my guesses
int inequality;//used to write if statements
for (int a = 0; a <= 10; a++)
{
cout << "Think about a number between 1-1000" << endl;//what console tells you
c = (big - small) / 2;//my guess will be the midpoint of the two numbers
while (big > small)//while the highest number is ALWAYS greater than the lowest number
{
cout << "Is your number less than, equal to, or greater than my guess? 1-less,2-equal,3-greater" << c << endl;
cin >> inequality;//you tell me whether my guess is too high, low, or equal
if (inequality == 1)//if you say it is too low...
{
small = c;//the smallest number is now my last guess
c = c - (big - small) / 2;//so, I'll take the midpoint of the CURRENT biggest and smallest number
}
else if (inequality == 2)//if you say it is equal...
{
cout << "Yay, I guessed your number." << endl;//cool.
}
else if (inequality == 3)//if you say it is too high...
{
big = c;//biggest number is now my guess
c = c + (big - small) / 2;//so, I'll take the midpoint of the CURRENT biggest and smallest number
}
}
}
system("pause");
return 0;//returns something in int main function
}
int main()
{
something();//so I can actually do code.
}
所以我的问题:
如果我在控制台输入第一次猜测后输入 1,我得到 499,这很好。第二次猜测后(我输入 1),我得到 249,这也很好。但是,我输入 1 后第三次猜测随机得到 681,所以有人可以帮助我吗?
如果您没有为我重写整个代码,我将不胜感激,否则当我上交时,这真的很可疑。我很挣扎,因为我没有很好的计算机科学背景,所以要改进,我主要需要想法。最后,任何能让我的代码看起来更专业一点的方法都将不胜感激:)
此外,我不确定我的 for 循环可能有点偏离。
最佳答案
当你计算下一个数字时你需要改变范围
所以你有第一个
small guess big
+---------+----------+
如果用户说太小,则答案高于猜测,因此在范围内
big - guess
这就是你需要切成两半的东西,而不是
c = c - (big - small)/2
guess = (big - guess) / 2 + guess
如果用户说太大,那么答案介于猜测和小之间
guess = (guess - small) / 2 + small
关于c++ - 计算机从 1 到 1000 猜测您的号码(必须尝试 10 次),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58576571/