This question already has answers here:
Is floating point math broken?
                                
                                    (31个答案)
                                
                        
                                2年前关闭。
            
                    
我宣布的金额为浮动金额。当我将值乘以100并将其插入“ int”变量时,该值将变为419 ...为什么会发生这种情况?

#include <stdio.h>
#include <cs50.h>
#include <math.h>

float amount;
int cents, coins, quarters, dimes, nickels, pennies, Q, D, N, P;
int main(void){

do
{
    amount = get_float("How much we talkin?\n");
}
while (amount < 0);
        printf("cents = %.55f\n", amount);
cents = amount * 100;
        printf("cents = %i\n", cents);
quarters = cents % 25;
    Q = cents / 25;
        printf("quarters = %i\n", quarters);
dimes = quarters % 10;
    D = quarters / 10;
        printf("dimes = %i\n", dimes);
nickels = dimes % 5;
    N = dimes / 5;
        printf("nickels = %i\n", nickels);
pennies = nickels % 1;
    P = nickels / 1;
        printf("pennies = %i\n", pennies);
coins = Q+D+N+P;

    printf("%i\n", coins);

}

~/workspace/pset1/cash/ $ ./cash
How much we talkin?
4.2
cents = 4.1999998092651367187500000000000000000000000000000000000
cents = 419
quarters = 19
dimes = 9
nickels = 4
pennies = 0
22


...该链接有所帮助。谢谢!

最佳答案

谢谢,我解决了这个问题,方法是将用户输入作为浮点数,将该值乘以100,然后四舍五入为最接近的整数。下面的代码有效,而不是世界上最干净的解决方案。

#include <stdio.h>
#include <cs50.h>
#include <math.h>

float amount;
int cents, coins, quarters, dimes, nickels, pennies, Q, D, N, P;
int main(void){

do
{
    amount = get_float("How much we talkin?\n");
}
while (amount < 0);
    // Print float input to see value is not precise
    printf("amount = %.55f\n", amount);

// Multiply amount by 100, then round to nearest
cents = roundf(amount * 100);
    printf("cents = %i\n", cents);

// *Quarters*
quarters = cents % 25;
    Q = cents / 25;
    printf("quarters = %i\n", Q);

// *Dimes*
dimes = quarters % 10;
    D = quarters / 10;
    printf("dimes = %i\n", D);

// *Nickels*
nickels = dimes % 5;
    N = dimes / 5;
    printf("nickels = %i\n", N);

// *Pennies*
pennies = nickels % 1;
    P = nickels / 1;
    printf("pennies = %i\n", P);

// Add up all the coins
coins = Q+D+N+P;

    printf("%i\n", coins);

}


~/workspace/pset1/cash/ $ ./cash
How much we talkin?
4.2
amount = 4.1999998092651367187500000000000000000000000000000000000
cents = 420
quarters = 16
dimes = 2
nickels = 0
pennies = 0
18

09-13 10:22