[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 271
  • Last Modified:

Help me complete this program ?

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
Hvt05
Asked:
Hvt05
  • 3
  • 2
  • 2
  • +1
1 Solution
 
gj62Commented:
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
 
KocilCommented:
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
 
KocilCommented:
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
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
yeeeooowwwCommented:
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
 
Hvt05Author Commented:
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
 
KocilCommented:
Very well tutorial yeeoooow.
nice.
0
 
Hvt05Author Commented:
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
 
yeeeooowwwCommented:
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

[Webinar] Kill tickets & tabs using PowerShell

Are you tired of cycling through the same browser tabs everyday to close the same repetitive tickets? In this webinar JumpCloud will show how you can leverage RESTful APIs to build your own PowerShell modules to kill tickets & tabs using the PowerShell command Invoke-RestMethod.

  • 3
  • 2
  • 2
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now