So I am using Visual Studio 2012 Professional, this is C++ code. I am just trying to get the remainder from a very simple division. Nothing difficult, heres the code:
1 2 3 4 5 6 7
double getProbability(){
int rd = random();
int max = numeric_limits<int>::max();
double result = rd % max;
cout << "Probability: " << result << "\n";
return result;
}
When I look at the values in debug I get:
1 2 3
max 2147483647
rd 1804289383
result 1804289383.0000000
Umm.... that is completely wrong. The answer should be 0.840188. What is going on here?
random() just returns a number from a vector that was prepopulated with "random" integers. Not really random, but that isn't all that important. What is important is why on earth is a % operation returning such a huge number. I assigned the values to variables so I could look at them in the debugger. I know I am going to probably get a thousand different ways that I could do this "better" but again, that isn't what I am looking for. I would just like someone to explain to me why the % operation is doing what it is doing?
So, when did % change from giving a remainder to doing what ever it is that is doing there? My understanding, and the way I have been using / and % for years is that / will give everything to the left of a decimal point, and % returns everything to the right of the decimal point, the remainder? I am honestly confused, I am not trying t be facetious or anything like that. This is honestly the first time I have ever seen a result like that from using %.
Just realized what was going on, this is what happens when you code on little sleep. The little things get you. The number is right, I just want the decimal at the other end of the number.
@Polorboy
I don't think you understand how modulus works http://www.cprogramming.com/tutorial/modulus.html
Modulus returns the remainder of integer division but if the numerator is smaller it is returned.