Hello guys, im doing this practice assignment from this book im reading about C++, im supposed to make a Coin Flip stimulation, and everything seems to be fine, its just im not quite sure of the way i've done it, so i need some opinions and possible some constructive criticism
Line 5 is OK for examples and quick tests, but make sure you know not to use it for real stuff. I assume you've heard this before and know why.
The main problem with your code is that it is possible none of the if statements will execute. Because you call randRange once for each condition, it generates a new value that could have fit a previous statement. Try using a switch-case instead.
Right; so each time randRange is called the coin is essentially being flipped again. You only ask the user once, but keep flipping the coin and changing the answer!
So that was the problem, cause i did noticed that the If statements were not executing properly, thank you very much for your time, i did modify the code a bit, and figured this would do just the right thing that its needed for me.
However, L B , can you be kind enough to explain what you mean about "not to use it for real stuff" , as im quite the beginner and i would love to know where its supposed to be used and where not :)
What i thought i did there, is that i simply created an int b that i would use to refer to the randRange(1,3) , so, now i could just use int b to compare for my If statements, was i right?
The only other thing I can see is that there's nothing to stop the user from entering something other than one or two, though it may not be something you're dealing with right now.
The possibilities are endless, for those who have been through it before :) , unfortunately this is my first time messing around with C++ , so those little tricks will come in time :D, but thanks for sharing, i must ask, what does this do, specifically?
b = rand()%2;
i know rand() calls out the random number, but %2 , what does it exatly mean?
#include <iostream>
#include <cstdlib>
#include <ctime>
usingnamespace std;
int randRange( int low, int high )
{
// do some error checking; avoid a possible divide by zero.
return low<high ? rand() % (high-low) + low : low ;
}
int main()
{
srand ( time(0) ) ;
// postpone defining a variable till we know how to initialize it
constint b = randRange(1,3) ; // and make it a const if it is never going to be modified
cout << "Hello, make your choice, Heads(1) or Tails(2) ?\n" ;
int a ;
if( cin >> a && a>0 && a<3 ) // make sure that the user has entered either 1 or 2
{
if( a==b ) cout << ( a==1 ? "Heads" : "Tails" ) << " it is!\n" ;
else cout << "Sorry, its " << ( a==1 ? "Tails" : "Heads" ) << " this time\n" ;
}
else std::cout << "error in input\n" ;
}
the (a==1 ? "Heads" : "Tails" ) i never knew i could do such a thing, nor do i know the explanation how it works or how its to be used... Sorry, but i havent read anything but this book that i got,so i might not be to well informed i guess...