1.13.3. Exercises: C++ Simple Types

[ fromfile: cppintro.xml id: x-simpletypes ]

  1. Write a short program that asks the user to enter a Celsius value and then computes the equivalent Fahrenheit temperature. It should use a QInputDialog to get the value from the user and a QMessageBox to display the result. After that, it should print out a table of Celsius to Fahrenheit values from 0 to 100 by increments of 5, to the console output.

  2. If you #include <cstdlib>, you can make use of the rand() function, which generates a sequence of uniformly distributed pseudo-random long int values in the range 0 to RAND_MAX. It works by computing the next number in its sequence from the last number that it generated. The function call

    srand(unsigned int seed)

    sets the first value of the sequence that rand() generates by to seed. Write a short program that tests this function. Ask the user to supply the seed from the keyboard and then generate a list of pseudo-random numbers.

  3. If you want your program's behavior to change each time you run it, you can use srand(time(0)) to seed the rand() function. Because the function call time(0) returns the number of seconds since some initial starting point, the seed will be different each time you run the program. This enables you to write programs that have usefully unpredictable behavior patterns.

    There is no particular advantage to calling srand() more than once when you execute your program. In fact, because a computer can do many things in a single second, repeated calls to srand() might even reduce the apparent randomness of your program.

    Write a program that simulates a dice game that the user can play with the computer. Here are the rules to apply to your game:

    • The game is about repeated "throws" of a pair of dice.

    • Each die has six faces, numbered 1 through 6.

    • A throw results in a number that is the total of the two top faces.

    • The first throw establishes the player's number.

    • If that number is 7 or 11, the player automatically wins.

    • If that number is 2, the player automatically loses.

    • Otherwise, the player continues throwing until she wins (by matching her number) or loses (by throwing a 7 or an 11).

  4. Write a program that accepts two values from the user (customer): the total purchase amount and the amount submitted for payment.

    Each of these values can be stored in a variable of type double. Compute and display the change that will be given to the user. Express the change in terms of the number of $10 bills, $5 bills, $1 bills, quarters, dimes, nickels, and pennies. (Presumably, this output could be sent to a machine that dispenses those items automatically.)

    For example, if the total purchase amount is $73.82 and the customer pays with a $100 bill, the change should be: two $10 bills, a $5 bill, a $1 bill, no quarters, a dime, a nickel, and three pennies.

    [Tip]Tip

    Convert the amount owed to the customer into pennies, which can be stored as an int. Use integer division operators.

  5. Write a program to play the following game, which the user plays against the computer.

    This game is played on an imaginary game board that has numbered spaces arranged in a circle.[20] For example, here is what a game board with 12 spaces might look like.

    • When the program starts, the user is asked to specify how many spaces there are on the game board. There must be at least five spaces.

    • The computer then randomly selects two spaces (excluding space numbers 0 and 1): One of the selected spaces is The Goal. The other is The Pit.

    • The computer announces the two special spaces.

    • Play then starts from space #0: Each player, in turn, "rolls" a pair of dice and "moves" to another space by advancing N spaces (where N is the number that came up on the dice). For example, using the sample game board with 12 spaces, if the user rolled a 10 (6 plus 4) on her first turn and a 7 (3 + 4) on her second turn, then she would land on space #5. That's where she would start on her next turn.

    • The user and the computer take turns rolling the dice and moving around the board. Each move is displayed on the screen (as text, not graphics; e.g., "You are now on space #3").

    • The game continues until one player lands on The Goal (and wins the game) or on The Pit (and loses the game).

    • The computer announces the outcome of each game and keeps track of each player's wins and losses.

    • The user can choose single play (user must press <Enter> for each roll of the dice) or continuous play (dice are automatically rolled and play continues until someone wins).

    • After each game the user can choose to quit or play another game.

    [Tip]Tip

    Do Problem 2 before attempting this problem. You may also need the suggestion at the beginning of Problem 3 and, perhaps, some ideas from that problem description.

     

    Example 1.29. solution/simpleTypesGame/game.cpp

    /*
    Board game rules:
       1. Obtain boardSize from command line or from user.
    	2. Designate two spaces for theGoal and thePit.
    	3. while (not gameOver)
    	4.   
    	       Player[i] rolls dice and has new position.
    	        if(Goal or Pit)
    			      gameOver is true
    					announce winner.
    			  else
    			      describe and record new position of Player[i]
    */
    #include <QTextStream>
    #include <QCoreApplication>
    #include <QStringList>
    #include <cstdlib>
    
    QTextStream cout(stdout);
    QTextStream cin(stdin);
     
    int diceRoll() {
       static const int FACES(6);
       int die1, die2;
       die1 = 1 + rand() % FACES;
       die2 = 1 + rand() % FACES;
       return die1 + die2;
    }
    
    int pitOrGoal(int spaces) {
       int res;
       while (1) {
          res = rand() % (spaces);
          if(res > 1)
             return res;
       }
    }
    
    int getSpaces(int argc, QCoreApplication& app) {
       const int MINSPACES(5);
       int spaces(0);
       QString ans;
       if(argc > 1) {
          QStringList arglst = app.arguments();
          spaces = arglst[1].toInt();
       }
       if(spaces < 5) {
          while(1) {
             cout << "How many spaces are on the game board? " << flush;
             ans = cin.readLine();
             spaces = ans.toInt();
             if(spaces > MINSPACES) 
                return spaces;
             else
                cout << "At least 5 spaces please ..." << endl;
          }
       }
       return spaces;
    }
    
    int currentGame(int spaces, int pit, int goal, bool continuous) {
       int pos0(0), pos1(0);  //Both players start on first space.
       QString ans;
       int roll;
       while(1) {
          roll = diceRoll();
          cout << "You throw " << roll << '\t' << flush;
          if(not continuous){
             ans = cin.readLine();
          }
          pos1 = (pos1 + roll) % spaces;
          if(pos1 == pit) {
             cout << "You fell into the pit - you lose!" << endl;
             return 0;
          }
          if(pos1 == goal) {
             cout << "You reached the goal! You win this one!" << endl;
             return 1;
          }
          cout << "You are now on space " << pos1 << endl;
          roll = diceRoll();
          cout << "I throw " << roll << '\t' << flush;
          if(not continuous){
             ans = cin.readLine();
          }
          pos0 = (pos0 + roll)% spaces;
          if(pos0 == pit){
             cout << "Arrgh! I'm in the pit - you win this one!" << endl;
             return 1; 
          }
          if(pos0 == goal) {
             cout << "I reached the goal!  I win this one!" << endl;
             return 0;
          }
          cout << "I am now on space " << pos0 << endl;
       }
    }
    
    
    int main(int argc, char** argv) {
       QCoreApplication app(argc, argv);
       int spaces(getSpaces(argc, app));
       srand(time(0));   //Set the seed for the rand() function.
       int pit(pitOrGoal(spaces));
       int goal(pitOrGoal(spaces));
       while(pit == goal)  // pit and goal must be separate spaces
          goal = pitOrGoal(spaces);
       cout << "The goal is on space " << goal << " and the pit is on space " << pit
            << endl;
       QString ans;
       cout << "Do you want continuous play (y/N)? " << flush; //No is default.
       ans = cin.readLine();
       bool continuous = (ans.toLower().startsWith('y'));
       // Computer is player0, human is player1
       int wins0(0), wins1(0), who;
       do {
          who = currentGame(spaces, pit, goal, continuous);
          if(who == 0)
             ++wins0;
          else
             ++wins1;
          cout << "So far: You have won " << wins1 << " games, I have won "
               << wins0 << " games.\n" << "Play another (y/N)? " << flush;
          ans = cin.readLine();
       } while(ans.toLower().startsWith('y'));
       cout << "Thanks for playing with me ... I get kinda lonely sometimes."
            << endl;
    }
    
    

    <include src="solution/simpleTypesGame/game.cpp" href="solution/simpleTypesGame/game.cpp" role="solution" mode="cpp"/>




[20] No graphics are required for this exercise. The game board is described only to help you picture the setup in your mind.