所以我在这里有以下代码段:
int main(int argc, char *argv[])
{
double cost;
sscanf(argv[1], "%lf", &cost);
double money_given;
sscanf(argv[2], "%lf", &money_given);
if(money_given < cost)
{
printf("Not enough money to cover the costs\n");
return -1;
}
float change = money_given - cost;
int quarters = change/.25;
int dimes = (change -0.25*quarters)/.10;
int nickels = (change -0.25*quarters - 0.1*dimes)/0.05;
int pennies = (change -0.25*quarters - 0.1*dimes - 0.05*nickels)/0.01;
printf("%f - 0.25*%d - 0.1*%d - 0.05 * %d\n", change, quarters, dimes, nickels);
printf("%d = pennies\n",pennies);
printf("Cost: %f, Money given: %f. \n Change: %f or \n %d quarters, %d dimes, %d nickels,"
" %d pennies\n", cost, money_given, change, quarters, dimes, nickels, pennies);
return 0;
}
因此,在这一行:
int pennies = (change -0.25*quarters - 0.1*dimes - 0.05*nickels)/0.01;
如果我将change变量声明为变量并且例如更改为0.46,则输出为:1个季度,2个角钱,0个镍币,0个便士,这是错误的。它应该是1个季度,2个角钱,0个镍币,1个便士。
当我将变量声明为浮点数时,我得到正确的答案。 这是为什么?当我使用double而不是float时,算术上有区别吗?