我在使用C语言编写程序时遇到了一些意想不到的行为,这些程序将钱转换为硬币。从最后3个printf()
输出中的输出块中可以看出,硬币为0,1.0000和0。
作为一个C新手,我不明白为什么int pennies_int = remainder / 0.01;
代码返回0而float pennies_float = remainder / 0.01;
返回1.000000。即使将float
值转换为int
,也会产生0值。
有人可以向我解释为什么float
1.000000值不会转换为int
1而显然包含1?
我正在使用Ubuntu clang version 3.6.0
并在Codepad上测试了相同的代码并获得相同的结果。
代码
#include <math.h>
#include <stdio.h>
int main (void)
{
float cash = 0.41;
float remainder;
int quarters = cash / 0.25;
remainder = fmod(cash, 0.25);
int dimes = remainder / 0.10;
remainder = fmod(remainder, 0.10);
int nickels = remainder / 0.05;
remainder = fmod(remainder, 0.05);
int pennies_int = remainder / 0.01;
float pennies_float = remainder / 0.01;
printf("Quarters: %i\n", quarters);
printf("Dimes: %i\n", dimes);
printf("Nickels: %i\n", nickels);
printf("Pennies (int): %i\n", pennies_int);
printf("Pennies (float): %f\n", pennies_float);
printf("Pennies (casted to int): %i\n", (int) pennies_float);
}
输出
Quarters: 1
Dimes: 1
Nickels: 1
Pennies (int): 0
Pennies (float): 1.000000
Pennies (casted to int): 0