I have an weird issue. I'm trying to store the result of an equation into a double variable.
double s = (((100 + 1)*(1/3))/100 + (1/3));
This returns a value a 0 rather than .67 (the correct value calculated from a calculator). Any reason why this could happen?
Note: A solution of saying that I could just make s = .67 is not a solution,
Thanks in advance.
The following uses integer (i.e. truncating) division, the result of which is zero:
1/3
To get floating-point division, turn either of the argument into a double, e.g.
1.0/3
Thus, the overall expression becomes:
double s = (((100 + 1)*(1./3))/100 + (1./3));
1. is the same as 1.0. Other ways to express the same number as a double are 1d and 1D.
The above expression evaluates to 0.6699999999999999.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With