![]() |
![]() |
#1 (permalink) |
Crazy
Location: Raleigh, NC
|
[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?
__________________
"Good artists copy, great artists steal." - Pablo Picasso |
![]() |
![]() |
#2 (permalink) |
Junkie
Location: San Francisco
|
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.
__________________
"Prohibition will work great injury to the cause of temperance. It is a species of intemperance within itself, for it goes beyond the bounds of reason in that it attempts to control a man's appetite by legislation, and makes a crime out of things that are not crimes. A Prohibition law strikes a blow at the very principles upon which our government was founded." --Abraham Lincoln |
![]() |
![]() |
#3 (permalink) |
<3 TFP
Location: 17TLH2445607250
|
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.
__________________
The prospect of achieving a peace agreement with the extremist group of MILF is almost impossible... -- Emmanuel Pinol, Governor of Cotobato My Homepage |
![]() |
![]() |
#5 (permalink) |
I am Winter Born
Location: Alexandria, VA
|
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.
__________________
Eat antimatter, Posleen-boy! |
![]() |
Tags |
floats, scanf |
|
|