Hi all,
I assign a value to a variable, i.e. float t=263.15; When I then print this variable, it is displayed as 263.149994. How can I declare/assign this variable differently so that it is not altered as such. Thanks.
Hi all,
I assign a value to a variable, i.e. float t=263.15; When I then print this variable, it is displayed as 263.149994. How can I declare/assign this variable differently so that it is not altered as such. Thanks.
Print it to 2 decimal places
The internal representation of the number is different from 263.15, and you cannot do much about that other than say, use a fixed point arithmetic library.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
Unfortunately the variable must exactly equal what I assign to it, otherwise the function that I call will not continue.
In that case, you should use an integer, not a floating point variable, or use a fixed point arithmetic library. If you cannot change this, then I'm afraid that the function that you are trying to call is broken by design.Originally Posted by bkms
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
Please post some code so we can see the right way to help for your situation.
My homepage
Advice: Take only as directed - If symptoms persist, please see your debugger
Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"
0.15 has an infinite expansion in binary. floats (and doubles) has a finite representation. If you need perfect representation of two decimal points, that's actually fixed-point, not floating-point, like laserlight said. So if you're representing money to the penny, for example, you would store it as pennies, 26315 pennies instead of 263.15 dollars. The only problem is printing it out and reading it in, but that's not too difficult.
The cost of software maintenance increases with the square of the programmer's creativity. - Robert D. Bliss
laserlight, I agree that the function is broken by design, since it requires an exact value to execute. I have found a temporary fix... instead of assigning the value within the program, I added some code so that 263.15 is scanned in from the keyboard when executing, and this works for now. Thanks, all, for your help.
This is probably another (float) vs. (double) issue. Why people still use (float) for anything is a mystery to me.