Note that there are some explanatory texts on larger screens.

plurals
  1. POBounds and whole numbers
    primarykey
    data
    text
    <p>I'm going through Bjarne Stroustrup's "Programming Principles and Practice Using C++". I am on chapter 4, exercise 4.</p> <p>The excercise is as follows:</p> <blockquote> <p>Write a program to play a numbers guessing game. The user thinks of a number between 1 and 100 and your program asks questions to figure out what the number is (e.g. "Is the number you are thinking of less than 50?"). Your program should be able to identify the number after asking no more than seven questions. Hint: Use the &lt; and &lt;= operators and if-else constructs.</p> </blockquote> <p>Now that is great, and I've managed to implement that fine.</p> <p>I'd thought I'd try and push myself and try and implement this using a loop and adjusting lower or upper bounds each time.</p> <p>Here is my code:</p> <pre><code>#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 &lt;&lt; count &lt;&lt;": Is your number between " &lt;&lt; lowerBound &lt;&lt; " and " &lt;&lt; lowerBound + halfRange &lt;&lt; "? "; cin &gt;&gt; userInput; // Reset the bounds if ( userInput == "y" || userInput == "Y" ) upperBound -= halfRange; else if ( userInput == "n" || userInput == "n" ) lowerBound += halfRange; else { --count; cout &lt;&lt; "Error! Answer could not be understood."; } } cout &lt;&lt; "lowerBound: " &lt;&lt; lowerBound &lt;&lt; ", upperBound: " &lt;&lt; upperBound &lt;&lt; "\n\n"; cout &lt;&lt; "Your number is: " &lt;&lt; lowerBound &lt;&lt; "\n"; return 0; } </code></pre> <p>The problem? Well, it occurs when it gets to numbers where there is a decimal portion and using integer division, which throws the decimal part away. If you use the number 48, the program guesses to 47 and 47.</p> <p>Any clues to get me going? I think I'm quite close, but will appreciate some help.</p> <p>Thanks,</p> <p>Matt</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload