我正在阅读 Bjarne Stroustrup 的“Programming Principles and Practice Using C++”。我在第 4 章,练习 4。
练习如下:
编写一个程序来玩数字猜谜游戏。用户想一个介于 1 和 100 之间的数字,您的程序会提出问题以找出该数字是多少(例如“您想的数字是否小于 50?”)。在询问不超过七个问题后,您的程序应该能够识别数字。提示:使用 < 和 <= 运算符和 if-else 结构。
现在这很好,我已经成功地实现了这一点。
我以为我会尝试推动自己并尝试使用循环并每次调整下限或上限来实现这一点。
这是我的代码:
#include "std_lib_facilities.h"
int main( ){
  int count = 0;
  int lowerBound = 0;
  int upperBound = 100;
  string userInput = "";
  while ( lowerBound != upperBound ){
    // Increment count
    ++count;
    int halfRange = 0;
    // Make halfRange a while number, round up if any decimal portion.
    double range = ( upperBound - lowerBound ) / 2;
    int rangeDelta = range - (int)range;
    if ( rangeDelta != 0 )
      halfRange = (int)range + 1;
    else
      halfRange = range;
    cout << count <<": Is your number between " << lowerBound << " and " << lowerBound + halfRange << "? ";
    cin >> userInput;
    // Reset the bounds
    if ( userInput == "y" || userInput == "Y" )
      upperBound -= halfRange;
    else if ( userInput == "n" || userInput == "n" )
      lowerBound += halfRange;
    else {
      --count;
      cout << "Error! Answer could not be understood.";
    }
  }
  cout << "lowerBound: " << lowerBound << ", upperBound: " << upperBound << "\n\n";
  cout << "Your number is: " << lowerBound << "\n";
  return 0;
}
问题?好吧,当它到达有小数部分的数字并使用整数除法时,就会发生这种情况,这会丢弃小数部分。如果使用数字 48,程序会猜测 47 和 47。
有什么线索可以让我走吗?我想我已经很接近了,但会感谢一些帮助。
谢谢,
马特