?
Solved

Help me complete this program ?

Posted on 2003-03-03
8
Medium Priority
?
270 Views
Last Modified: 2010-04-01
I can't get my program to loop for the wrong answer. And how do you calculate the total percentage for the number of right answers that the user gets.

Here is my code

#include <iostream>
#include <ctime>
#include <iomanip>
#include <cstdlib>

using std::cout;
using std::cin;
using std::endl;
using std::setw;

int main()
{
int home, home1, home2, home3;
char answer2;
unsigned answer1;

srand ( time( 0 ));

cout << "Welcome to Learn How To Multiply for Elementary students\n";
cout << "Please enter y to continue or n to quit: ";
cin >> answer2;

while ( answer2 != 'n' || 'N' ){

if ( answer2 == 'y' || 'Y' ){

home = (rand() % 10 );
home1 = (rand() % 10 );

cout <<"What is "<< home <<" times "<< home1 << " : ";
cin >> answer1;

if( answer1 == home * home1 ){

home2 = 1 + rand() % 4 ;

switch ( home2 ){
case 1:
cout << "Very good!! " << endl;
break;

case 2:
cout << "Excellent!! " << endl;
break;

case 3:
cout << "Nice work!! " << endl;
break;

case 4:
cout <<"Keep up the good work!! " << endl;
break;
}}

if( answer1 != home * home1 ){

home3 = 1 + rand() % 4 ;

switch ( home3 ){
case 1:
cout <<"No. Please try again.\n";
cout <<"Would you like to play again, y/n " << endl;

break;
case 2:
cout <<"Wrong. Try once more.\n";
cout <<"What is " << home <<"times " << home1 << ":";
cout <<"Would you like to play again, y/n " << endl;
cin >> answer1;
break;
case 3:
cout <<"Don't give up.\n";
cout <<"What is " << home <<"times " << home1 << ":";
cout <<"Would you like to play again, y/n " << endl;
cin >> answer1;
break;
case 4:
cout <<"No. Keep trying.\n";
cout <<"What is " << home <<"times " << home1 <<":";
cout <<"Would you like to play again, y/n " << endl;
cin >> answer1;
break;
cout <<"What is " << home <<" times "<< home1 <<":";
cout <<"Would you like to play again, y/n " << endl;
cin >> answer1;
}}
}}

return 0;
}
0
Comment
Question by:Hvt05
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
  • 2
  • +1
8 Comments
 
LVL 6

Expert Comment

by:gj62
ID: 8062061
First, you can't capture an int using cin>>answer1

Instead, define answer 1 as

char answer1[30]; or something like that

you can change it to an int where needed by doing

atoi(answer1);

That will stop your forever loops when you get a bad answer.

Your program still is odd because it asks if you want to quit only after a bad answer, but doesn't test for it - I will leave that as work for you to do - but let me know if you need help with it...
0
 
LVL 5

Expert Comment

by:Kocil
ID: 8062088
Question 1, about the loop

while ( answer2 != 'n' || 'N' ){..}

should be

while ( (answer2 != 'n') || (answer2 != 'N') ){..}
or
while ( toupper(answer2) != 'N') ){..}

The same with the
if ( answer2 == 'y' || 'Y' ) {..}


Question2, to count the percentation,

main()
{
   /* Add 2 variables */
   int total=0, correct=0;

   while (toupper(answer(2) != 'N') {
     /* if play then increment total */
     if ( toupper(answer2) 'Y' ){
        total++;
        home = (rand() % 10 );
        .....

        /* if correct then increment correct */
        if( answer1 == home * home1 ){
           correct++;
           home2 = 1 + rand() % 4 ;
           ...
        }
        else { /* wrong */ }
     }
   } /* end while */
   /* count percentage here */
   printf("Percentage = %f\n", 100*correct/total);
}

Looks like a nice program for your little kid :)
Good luck

 
0
 
LVL 5

Expert Comment

by:Kocil
ID: 8062117
Oops, correction

main()
{
  /* Add 2 variables */
  int total=0, correct=0;

  while (toupper(answer(2) != 'N') {
    /* if play then increment total */
    /****** missing == ******/
    if ( toupper(answer2) == 'Y' ){
       total++;
       home = (rand() % 10 );
       .....

       /* if correct then increment correct */
       if( answer1 == home * home1 ){
          correct++;
          home2 = 1 + rand() % 4 ;
          ...
       }
       else { /* wrong */ }
    }
  } /* end while */
  /* count percentage here */
  /***** only if total is not zero *****/
  if (total > 0) printf("Percentage = %f\n", 100*correct/total);
}

0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Accepted Solution

by:
yeeeooowww earned 380 total points
ID: 8064070
Oh my god!!
Forgive me for asking this.. but is this the first program you are writing in any programming language?!!

There is something called functions use them to segregate various functional aspects of your programs... it is very bad logic to dump everything in one main function call.

and add some documentation to your code.

here's a working code segment that I have edited for you. try to model your code on this in the future!!

#include <iostream>
#include <ctime>
//#include <iomanip>  - this file is not needed
#include <cstdlib>

using std::cout;
using std::cin;
using std::endl;
using std::setw;

void congrats (int);   // pick a random congrats message
void regret (int);     // pick a ranmdom regret message

int main()
{
int home, home1, home2, home3;
char answer2;
unsigned answer1;

srand ( time( 0 ));

cout << "Welcome to Learn How To Multiply for Elementary students\n";
cout << "Please enter y to continue or n to quit: ";
cin >> answer2;

while ( answer2 == 'y' || answer2 == 'Y' ){

   home = (rand() % 10 );
   home1 = (rand() % 10 );

   cout <<"What is "<< home <<" times "<< home1 << " : ";
   cin >> answer1;

   home2 = 1 + rand() % 4 ;

   if( answer1 == home * home1 )
   congrats (home2);    // call congrat() to indicate correct answer
   else
   regret (home2);  // call regret() to indicate error

   cout <<"Would you like to play again, y/n: ";
   cin >> answer2;
}


return 0;
}

void congrats (int CongratPicker)
{
switch ( CongratPicker ){
case 1:
cout << "Very good!! " << endl;
return;

case 2:
cout << "Excellent!! " << endl;
return;

case 3:
cout << "Nice work!! " << endl;
return;

case 4:
cout <<"Keep up the good work!! " << endl;
return;
}
}

void regret (int regretPicker)
{
switch ( regretPicker ){

case 1:
cout <<"No. Please try again.\n";
return;

case 2:
cout <<"Wrong. Try once more.\n";
return;

case 3:
cout <<"Don't give up.\n";
return;

case 4:
cout <<"No. Keep trying.\n";
return;
}
}
0
 

Author Comment

by:Hvt05
ID: 8074326
Thank you very much!
Yeah! this is the fist time that I try to write codes for such complicated program.

But how do you repeat the question that the users answer wrong.  This must keeps repeating until they got it right?
Then calculate the percentage of the answers that they answer correctly.
0
 
LVL 5

Expert Comment

by:Kocil
ID: 8075079
Very well tutorial yeeoooow.
nice.
0
 

Author Comment

by:Hvt05
ID: 8084672
Hey yeeoooow, what's wrong with this program?
can you debug it for me.  And show me how u would use #include <windows.h> to clear the screen whenever the user wins and continue on with the game.

Here's the program (the Craps game)

#include <iostream>                                                            // iostream header file
#include <windows.h>
#include <cstdlib>            // contains function prototypes for functions srand and rand
#include <ctime>            // contains prototype for function time


using std::cout;                                                            // program uses cout
using std::endl;                                                            // program uses endl
using std::cin;

void regrets (int);
void congrats (int);
int Game (void);
int rollDice( void );                                                      // function prototype

int main()                                                // function main begins program execution
{
   
   enum Status { CONTINUE, WON, LOST };      // enumeration constants represent game status

   int num, sum, wager;                                                      // declared
   int home, home1;
   int myPoint;                                                                  // declared
   int bankBalance = 1000;                                                // initialize
   int newbankBalance;

   Status gameStatus;                  // can contain CONTINUE, WON or LOST
   srand( time( 0 ) );                  // randomize random number generator using current time
   sum = rollDice();                                                      // first roll of the dice

   cout <<"You have $1000 in the bank " << endl;
   
   while (bankBalance = 1000)
            cout <<"Please enter a wager: " << endl;
            cin >> num;
      if( wager > 1000 || wager < 0)
            cout <<"Please bet a valid amount" << endl;
            cin >> num;
            Game ((int) sum);
                  
                  home = 1 + rand() % 2;
                  if( gameStatus == WON )
                        congrats (home);
                        newbankBalance = bankBalance + wager;
                        cout <<"Your bankBalance is" << newbankBalance << endl;
                  else
                        regrets (home);
                        newbankBalance = bankBalance - wager;
                  if( newbankBalance = 0 )
                        cout <<"Sorry. You busted!" << endl;


      
      int Game ( int sum ) {      
   switch ( sum ) {            // determine game status and point based on sum of dice
            
                                                                                    // win on first roll
      case 7:                  
         case 11:            
         gameStatus = WON;
         break;
                                                                                    // lose on first roll
      case 2:
         case 3:
         case 12:            
         gameStatus = LOST;
         break;
                                                                                    // remember point
      default:                   
         gameStatus = CONTINUE;
         myPoint = sum;
         cout << "Point is " << myPoint << endl;
         break;                                                                  // optional  

   }                                                                              // end switch

   while ( gameStatus == CONTINUE ) {                              // while game not complete ...
      sum = rollDice();                                                      // roll dice again

                                                                                    // determine game status
      if ( sum == myPoint )                                                // win by making point
         gameStatus = WON;
      else
         if ( sum == 7 )                                                // lose by rolling 7
            gameStatus = LOST;

   }                                                                              // end while

                                                                                    // display won or lost message
   if ( gameStatus == WON )
      cout << "Player wins" << endl;
   else
      cout << "Player loses" << endl;

   return 0;                                                      // indicates successful termination

}                                                                                    // end main

                                                            // roll dice, calculate sum and display results
int rollDice( void )
{
   int die1;
   int die2;
   int workSum;

   die1 = 1 + rand() % 6;                                                // pick random die1 value
   die2 = 1 + rand() % 6;                                                // pick random die2 value
   workSum = die1 + die2;                                                // sum die1 and die2

                                                                                    // display results of this roll
   cout << "Player rolled " << die1 << " + " << die2
        << " = " << workSum << endl;

   return workSum;                                                            // return sum of dice

}                                                                                    // end function rollDice

return 0;
}

void congrats (int CongratPicker) {
      switch (CongratPicker) {
      case 1:
            cout <<"Now's the time to cash in your chips!" << endl;
            break;

      case 2:
            cout <<"Wow. You're so lucky!" << endl;
            break;
      }
}

void regrets (int SorryPicker) {
      switch (SorryPicker) {
      case 1:
            cout <<"Oh, you're going for broke, huh?" << endl;
            break;
            
      case 2:
            cout <<"Aw cmon, take a chance!" << endl;
            break;
      }
}

0
 

Expert Comment

by:yeeeooowww
ID: 8103979
Hi,

Nice going...
I didn't check my mail during the weekend and hence the delayed response..

Seems like you have gone forward quite a bit..!! ;)

and remember, function names can change and there's something called Hungarian Notation.. if you are usign VC++ or u can invent some standard convention of naming your variables and functions.. this will increase readability...

ooohhh.... I just started reading your code and there is this thingy called parentheses in C ?!! (and c++ and every programming language in this universe?!! LOL just kidding)

You should probably get a good book (something very basic on C/c++)and should be very comfortable with syntax.. that'll help in avoiding so many compiler errors.... there should be braces '{' and '}' enclosing all those statements that need to be executed if an 'if' condition succeeds and the same holds true for else too...

The following code should work....


#include <iostream.h>
#include <cstdlib>
#include <ctime>
#include <conio.h>

using std::cout;                                                  // program uses cout
using std::endl;                                                  // program uses endl
using std::cin;

void regrets (int);
void congrats (int);
int RollDice( void );                                             // function prototype
int GetBetValue(void);

int main()                                        // function main begins program execution
{
 
  enum Status { CONTINUE, WON, LOST };     // enumeration constants represent game status

  int n_BetPlaced, n_BetValue, n_DiceValue;
  int home;
  int bankBalance = 1000;                                        // initialize

  Status gameStatus;               // can contain CONTINUE, WON or LOST

  srand( time( 0 ) );               // randomize random number generator using current time

  cout <<"You have $1000 in the bank " << endl;
  while (bankBalance > 0)
  {
        cout <<"Please enter a bet: " << endl;
        cin >> n_BetPlaced;
        while(n_BetPlaced <= 0)
        {
        cout << "You have to place a bet to play this game:" << endl;
        cin >> n_BetPlaced;
        }
        while(bankBalance - n_BetPlaced < 0)
        {
        cout <<"You don't have that much money to bet!!" << endl << "Please Enter a valid bet:";
        cin >> n_BetPlaced;
        }

        n_BetValue = GetBetValue();
        n_DiceValue = RollDice();
               
        home = 1 + rand() % 2;
        if( n_BetValue == n_DiceValue)
        {
            congrats (home);
            bankBalance += n_BetPlaced;
            cout <<"Your bankBalance is" << bankBalance << endl;
        }
        else
        {
            regrets (home);
            bankBalance -= n_BetPlaced;
            cout <<"Your bankBalance is" << bankBalance << endl;
        }

  }     // end of while
  cout <<"Sorry. You busted!" << endl;
}       // end of main()

int GetBetValue(void)
{
    int n_Value = 1;

    do
    {
         cout << "1. Bet on Less than 7" << endl;
         cout << "2. Bet on equal to 7" << endl;
         cout << "3. Bet on greater than 7" << endl;
         cout << "Please Enter your option:";
         cin >> n_Value;
    }while((n_Value < 1) || (n_Value > 3));

    return n_Value;
}

// roll dice, calculate sum and display results
int RollDice( void )
{
  int die1;
  int die2;
  int workSum;

  die1 = 1 + rand() % 6;   // pick random die1 value
  die2 = 1 + rand() % 6;   // pick random die2 value
  workSum = die1 + die2;   // sum die1 and die2

  // display results of this roll
  cout << "Player rolled " << die1 << " + " << die2 << " = " << workSum << endl;

  if (workSum < 7)
  {
     return 1;
  }
  else if (workSum == 7)
  {
     return 2;
  }
  else
  {
     return 3;
  }

  // return 0 1 if less than 7, 2 if equal to 7, and 3 if
  //greater than 7
}                                                                      // end function rollDice

void congrats (int CongratPicker) {
 switch (CongratPicker) {
 case 1:
  cout <<"Now's the time to cash in your chips!" << endl;
  break;

 case 2:
  cout <<"Wow. You're so lucky!" << endl;
  break;
 }
}

void regrets (int SorryPicker) {
     switch (SorryPicker) {
     case 1:
      cout <<"Oh, you're going for broke, huh?" << endl;
      break;
         
     case 2:
      cout <<"Aw cmon, take a chance!" << endl;
      break;
     }
}
0

Featured Post

On Demand Webinar - Networking for the Cloud Era

This webinar discusses:
-Common barriers companies experience when moving to the cloud
-How SD-WAN changes the way we look at networks
-Best practices customers should employ moving forward with cloud migration
-What happens behind the scenes of SteelConnect’s one-click button

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Article by: SunnyDark
This article's goal is to present you with an easy to use XML wrapper for C++ and also present some interesting techniques that you might use with MS C++. The reason I built this class is to ease the pain of using XML files with C++, since there is…
This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.
Suggested Courses

741 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question