Hi guys, I solved this C++ problem for my mid semester assignment. It is a guessing game where the user will guess a number between 1 and 10 and will bet and win/lose money accordingly.
I just started programing with C++ so I'd like to receive feedback on how to optimize/polish my code.
#include <iostream>
#include <iomanip>
#include <ctime>
using namespace std;
int main()
{
//declare variables
float balance = 100; //initial balance
float bet; //bet value
int guessNumber; //The number user guess is an integer (1-10)
int computerNumber; //The number computer randomly generate is an integer (1-10)
float loseDollars; //the amout of dollars to lose when giving a wrong guess
//welcome message
cout << "CP1200 Guessing Game" << endl;
cout << "Written by " << endl << endl;
//formatted in the standard way with two decimal places
cout << fixed << setprecision(2);
//input the bet
cout << "Please enter your bet (up to $" << balance << "): $";
cin >> bet;
srand( time(0) ); // set the seed of random variables
//main guessing and betting procedure
while( (bet != 0) && (balance > 0))
{
// check the validity of betting
if( (bet > balance) || (bet < 0) )
{
bet = balance;
cout << "Your bet is $" << bet << endl;
}
cout << endl << "Guess a number between 1 and 10: ";
cin >> guessNumber;
computerNumber=1 + rand() % 10; // generate a random value from 1 to 10
// correct guess
if( guessNumber == computerNumber )
{
cout << endl << "Correct!" << endl;
cout << "You win $" << bet << endl<<endl;
balance = balance + bet;
}
//wrong guess
else
{
cout << endl << "Wrong! The computer chose: " << computerNumber << endl;
loseDollars = bet / 5.0 * abs( guessNumber - computerNumber );
if (loseDollars >= balance)
{
cout << "You lose $" << balance << endl << endl;
balance = balance - loseDollars;
}
else
{
cout << "You lose $" << loseDollars << endl << endl;
balance = balance - loseDollars;
}
}
// check the balance after guess
if( balance > 0 )
{
cout << "Your new balance is $" << balance << endl << endl;
cout << "Please enter your bet (up to $" << balance << "): $";
cin >> bet;
}
}//end while
//farewell message
cout <<endl<< "Thank you for playing!" << endl;
system("pause");
return 0;
} //end of main function