货币值花车比较不起作用 [英] Comparing currency values as floats does not work
本文介绍了货币值花车比较不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我输入0.01或0.02的程序只是立即退出。我该怎么办?谢谢你。
我的帖子主要是code。我需要添加一些更多的细节。
的#include<&stdio.h中GT;焦线[100];
浮动量;诠释的main()
{
的printf(请输入的金额:);
与fgets(行,sizeof的(线),标准输入);
sscanf的(行,%F,&安培;金额);如果(金额== 0.0)
的printf(宿舍:0 \\ nDimes:0 \\ nNickels:0 \\ nPennies:0);如果(金额== 0.01)
的printf(宿舍:0 \\ nDimes:0 \\ nNickels:0 \\ nPennies:1);
如果(金额== 0.02)
的printf(宿舍:0 \\ nDimes:0 \\ nNickels:0 \\ nPennies:2);返回(0);
}
解决方案
您的声明比较价值为float。
如果(金额== 0.01F)
的printf(宿舍:0 \\ nDimes:0 \\ nNickels:0 \\ nPennies:1);
请注意,你可以通过直接测试浮点平等遇到一些不确定的行为,如果你与你的浮点变量做了一些计算。
If I type 0.01 or 0.02 the the program just exits immediately. What do I do? Thanks.
my post is mostly code. I need to add some more details.
#include <stdio.h>
char line[100];
float amount;
int main()
{
printf("Enter the amount of money: ");
fgets(line, sizeof(line), stdin);
sscanf(line, "%f", &amount);
if (amount == 0.0)
printf("Quarters: 0\nDimes: 0\nNickels: 0\nPennies: 0");
if (amount == 0.01)
printf("Quarters: 0\nDimes: 0\nNickels: 0\nPennies: 1");
if (amount == 0.02)
printf("Quarters: 0\nDimes: 0\nNickels: 0\nPennies: 2");
return (0);
}
解决方案
Declare your comparative value as a float.
if (amount == 0.01f)
printf("Quarters: 0\nDimes: 0\nNickels: 0\nPennies: 1");
Note that you could encounter some undefined behavior by directly testing float equality if you made some calculations with your float variable.
这篇关于货币值花车比较不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文