I'm an amateur korean c++ learner, and am trying to make a fully working coin tossing program. Since I'm now studying rand() function, I want to define the heads and tails using the remainder of dividing a random number with 2. That way, I would probably get either 0 or 1 as a result, which I can use to decide whether the result would be head or tail. But for some occasion it seems that I'm getting results other than 0 or 1.
int random()
{
return rand()%2;
}
I defined a function that would produce the remainder..
int seed=time(NULL);
srand(seed);
cout << "The seed is: " << seed << "\n";
cout << "Press any key to toss a coin.\n";
cin.get();
if(random()==0)
{
cout << "Head!\n";
}
else if(random()==1)
{
cout << "Tail!\n";
}
else
{
cout << "ERROR DETECTED\n";
return 0;
}
..and wrote the main function.
I added the last part so that I can spot the error that I mentioned above.
I noticed the "ERROR DETECTED" showing up for plenty of times. It just seems odd to me since dividing a random number with 2 cannot produce a remainder other than 0 or 1.
You are generating two separate random numbers for the if and the else part. Instead, set a variable to the return value of random() and use that in the tests.
random() actually is generating only numbers 0 or 1. Let's look at your code.
1 2 3 4
if (random() == 0) //generates a random number and checks if it is zero
//do stuff
elseif (random() == 1)// generates a NEW random number and checks if it is one
//do stuff
You want to generate only one random number, store it in a variable and check the value of that variable.
Prior to C++11, the behaviour was implementation defined:
If both operands are non-negative then the remainder is non-negative; if not, the sign of the remainder is implementation-defined.
With C++11, the behaviour is well defined (same sign as the dividend):
For integral operands the / operator yields the algebraic quotient with any fractional part discarded; if the quotient a/b is representable in the type of the result, (a/b)*b + a%b is equal to a.
Yes, that is good to know from a computational perspective.
However, if dealing with modular arithmetic from a pure maths perspective then it's not so clear cut. If I was working modulo 5 then I would expect the only possible values to be 0, 1, 2, 3, 4. If I were working modulo 2 then I would expect the only elements to be 0 and 1. However, this operation produces -1. Moreover, in modulo 5, the number 3 has only one additive inverse (namely 2); however, thanks to the computational definition here, it has two (2 and -3). This actually cripples quite a lot of group-theory results.
Perhaps % would be better called the remainder operator, not the modulo operator. It really depends whether you are deliberately trying to compute remainders or to cycle. Many languages have separate functions for each.
And, at the time of writing, yesterday was Wednesday, not "minus Friday".
Is "implementation-defined" a kindly euphemism for "undefined behaviour"?