Basic question, the code is very large, but my issue is, at it’s core, basic :
I have a double value known as variable, and if I check it with cout << variable, it will give me, for example, 982.
The very next line of code is int intvariable = variable.
Then, when I check it with cout << intvariable, I’m given 981.
The funny thing is, this doesn’t always happen. With 985 it might stay at 985, but then at 984 and 983, it will return 983 and 982. I can’t seem to figure this out at ALL. I’ve tried converting it to a float and then to an int, or to another double and then an int.
I need it as an int so I can use the modulus operator with it.
I should point out, previously in the code the double is less than 1 (i.e, 0.987), and is then multiplied by the number of decimal places to make it a real, positive integer (though, it’s stored as a double still at that point). Maybe that has something to do with the random rounding?
Casting a floating point value to an
intwill truncate (return the floor of) the value, possibly leading to your problems because floating point numbers are inherently imprecise. Try rounding the number instead, i.e.intvariable = (int)(0.5 + variable). You might also be interested in thefmodfunction, which computes the remainder of floating point division (see http://www.cplusplus.com/reference/cmath/).