![]() |
[c] scanf and floats
I am using scanf to enter a float as follows:
float paymentAmount = 0.0; (void) scanf ("%f", &paymentAmount); When I enter a value such as 13.46 the standard printf shows something like 13.46000000 but if I set the printf to show more places it turns out that the stored number is really 13.4600000012343542.... this is throwing off my calculations.. Any suggestions as to why those random numbers are at the end of my float? |
Yes, that's the actual value of the stored number. As a consequence of limited accuracy, it's impossible to precisely represent all real numbers, and as a consequence of the binary floating point format, this includes many numbers that "look nice" in decimal such as 13.46. The computer does the best it can in giving you the closest value that is possible. If you need more accuracy, you can use doubles, but integers are the only built-in types that will give you exact accuracy (at the cost of range). For example, you can represent dollar values in terms of integer cents instead of decimal dollars.
|
You could also force it to always only look at 2 decimal places. If you are doing a calculation to say add two numbers (not likely where your math goes wonky, but it works just the same), instead of doing:
$sum = $a + $b you can do something like: $sum = round($a, 2) + round($b, 2) The above example is in PHP, but I'm sure C has a similar function. This will round $a to say, 13.46 instead of 13.46000000 or 13.46000001234542 and will perform the math on that value. |
how about using an integer, and making it represent cents instead of dollars?
|
You may be able to do scanf( "%d.%d", &intOne, &intTwo); and that should work, assuming you instruct the user to enter it in the format of "XX.XX", where the Xes are obviously integers. Not sure 100% sure how to get around the float issue, my C is a little rusty at the moment.
|
Use doubles
If you just want more accuracy, use doubles. I think printf/scanf need %fl in that case.
|
Quote:
|
All times are GMT -8. The time now is 02:03 PM. |
Powered by vBulletin® Version 3.8.7
Copyright ©2000 - 2025, vBulletin Solutions, Inc.
Search Engine Optimization by vBSEO 3.6.0 PL2
© 2002-2012 Tilted Forum Project