将货币价值作为浮动进行比较不起作用 [英] Comparing currency values as floats does not work

查看:29
本文介绍了将货币价值作为浮动进行比较不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我输入 0.01 或 0.02,程序会立即退出.我该怎么办?

If I type 0.01 or 0.02 the the program just exits immediately. What do I do?

#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
Dimes: 0
Nickels: 0
Pennies: 0");

if (amount == 0.01)
   printf("Quarters: 0
Dimes: 0
Nickels: 0
Pennies: 1");


if (amount == 0.02)
   printf("Quarters: 0
Dimes: 0
Nickels: 0
Pennies: 2");

return (0);
}

推荐答案

对这个答案的反对票是当之无愧的,它错误地提倡简单的平等测试.虽然这是未定义的行为,不应该被鼓励,但即使如此,它也会有时起作用.

The downvotes on this answer are well deserved, it was wrongly advocating for a simple equality test. While this is undefined behaviour and should not be encouraged, even so it happens to work sometimes.

您永远不应该测试浮动值的相等性.而是使用 epsilon 值根据范围测试您的变量,因为 this answer 建议这样做.

You should never test a floating value for equality. Instead use an epsilon value to test your variable against a range as this answer is suggesting it.

例如以这个例子:

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

#define  EPSILON 0.00001f

int main() {
    float a = 3.234324333f;
    float b = a;
    b += 1;
    b -= 1;
    
    printf("a value is %f
", a);
    printf("b value is %f
", b);

    printf("
a == b ?
");
    if (a == b) {
        printf("true
");
    } else {
        printf("false
");
    }

    printf("a ~= b with epsilon = %f ?
", EPSILON);
    if (fabs(a - b) <= EPSILON) {
        printf("true
");
    } else {
        printf("false
");
    }
    return 0;
}

运行时:

a value is 3.234324
b value is 3.234324

a == b ?
false
a ~= b with epsilon = 0.000010 ?
true

这篇关于将货币价值作为浮动进行比较不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆