I have a win/lose game in c++. My problem is that at the beginning, after I set the y
value, my code does two rounds, but I want it to do only one. I don't understand why, so I need help. This is the only problem that I am having. The code is here:
#include <iostream>
#include <ctime>
#include <conio.h>
using namespace std;
int main()
{
int x, y, wins = 0, fails = 0;
char key;
srand(time(NULL)); // seed for random number generation
cout << "Enter the value of y (1-200): ";
cin >> y;
while (true)
{
double prob = (double)y / 20.0; // calculate probability
double rand_num = (double)rand() / RAND_MAX; // generate a random number between 0 and 1
x = (rand_num < prob) ? 1 : 0; // determine if player has won or lost
if (x == 1)
{
cout << "Congratulations, you won 100000 dollars!!!\n";
wins++;
}
else
{
cout << "You lost, try again...\n";
fails++;
}
cout << "Wins: " << wins << ", Fails: " << fails << endl;
key = getch(); // wait for user input
if (key == 'q' || key == 'Q')
{
continue; // generate a new random number
}
else if (key == 'r' || key == 'R')
{
wins = fails = 0; // reset variables
}
}
return 0;
}
This is what appears on the console after i set the y value ( in this example:6) and press Enter:
Enter the value of y (1-200): 6
You lost, try again...
Wins: 0, Fails: 1
You lost, try again...
Wins: 0, Fails: 2