Mar 23, 2019 at 4:40pm Mar 23, 2019 at 4:40pm UTC
How can I make the program run over again without closing the console?
And also, can I make it output "invalid syntax" if it is not an integer?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
#include <time.h>
#include <stdlib.h>
using namespace std;
int main() {
int a, b;
srand(time(NULL));
a = rand() % 3 + 1;
cout << "Int 1-3\n" ;
cin >> b;
if (b == a) cout << "Success!\n" ;
else cout << "Failure!\n" ;
}
Last edited on Mar 23, 2019 at 4:41pm Mar 23, 2019 at 4:41pm UTC
Mar 23, 2019 at 4:42pm Mar 23, 2019 at 4:42pm UTC
A while or do-while loop.
Mar 23, 2019 at 5:24pm Mar 23, 2019 at 5:24pm UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <stdexcept>
// Reading numbers by discarding all mismatching inputs
// is a little bit tricky:
//
int read_int(std::istream & is)
{
while (true )
{
std::string tmp;
int number;
while (std::getline(is, tmp))
{
try {
number = std::stoi(tmp);
}
catch ( std::invalid_argument & e)
{
std::cout << "Invalid syntax.\n" ;
continue ;
}
return number;
}
throw std::runtime_error("Couldn't read from istream!\n" );
}
}
int main()
{
int a, b, win{}, loss{}, c{}; // win,loss, c will initialized to 0
std::srand(std::time(nullptr ));
while (c++ < 100)
{
a = std::rand() % 3 + 1;
std::cout << "Int 1-3\n" ;
b = read_int(std::cin);
if (b == a)
{
std::cout << "Success!\n\n" ;
++win;
}
else
{
++loss;
std::cout << "Failure!\n\n" ;
}
std::cout << "RWP = " << double (win) / (win + loss) << '\n' ;
}
}
Last edited on Mar 23, 2019 at 6:06pm Mar 23, 2019 at 6:06pm UTC
Mar 23, 2019 at 6:28pm Mar 23, 2019 at 6:28pm UTC
In the code you've shown there is no place where it will divide by 0, so you were probably running some other code.
Anyway, you should put srand before the loop (you don't want to seed the RNG every iteration).
And you need to initialize win and loss before the loop, too.
And your calculation with the float needs to be done in floating point, which requires a cast on one of the integer operands.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
#include <iostream>
#include <cstdlib>
using namespace std;
const int NumTries = 100;
int main() {
srand(time(0));
int wins = 0;
for (int tries = 0; tries < NumTries; ++tries) {
int a = rand() % 3 + 1;
cout << "Int 1-3\n" ;
int b;
cin >> b;
if (b == a) {
cout << "win\n" ;
++wins;
}
else
cout << "loss\n" ;
cout << "RWP = " << float (wins) / (tries + 1) << '\n' ;
}
}
Last edited on Mar 23, 2019 at 6:29pm Mar 23, 2019 at 6:29pm UTC
Mar 23, 2019 at 6:52pm Mar 23, 2019 at 6:52pm UTC
Ok thanks, but how can I make a statement such as "if a > 0 and b>0 and c>0" in one line of code not three different if statements
Mar 23, 2019 at 7:22pm Mar 23, 2019 at 7:22pm UTC
if ( (a > 0) && (b>0) && (c>0) )