Ç - 比较花车if语句 [英] C - Comparing floats with if statements

查看:83
本文介绍了Ç - 比较花车if语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在写一个贪心算法,但比较花车的时候我已经在一个问题绊倒了。

I am currently writing a greedy algorithm, but I have stumbled upon a problem when comparing floats.

我会用code是这样的:

I would use code like this:

float f = 0;   

if (f == 0) {
   // code
}

我已经在我的工作程序在一个单独的程序测试这一点,它工作得很好,但不是。

I have tested this on a seperate program and it worked fine, but not on the program I am working on.

下面是从我自己的程序中提取。

Here is an extract from my own program.

float chf2 = fmod(chf, 0.1);
float ch3 = chf - chf2;

if (chf2 == 0) {

    /* Divide user's number by 0.1 */

    float ch3 = chf / 0.1;

    /* Round the number */

    int ch4 = round(ch3);

    /* Print the amount of coins and end */

    printf("%d\n", ch4 + coin2);
    return 0;
}

奇怪的是,这似乎与检查​​一个previous if语句来上班的时候0.25从用户的输入FMOD。

Oddly, this seems to work with a previous if statement that checks when a fmod of 0.25 from the user's input.

有没有检查,如果一个浮动等于另一个浮动一个更好的办法?

Is there a better way of checking if a float is equal to another float?

推荐答案

您code正常工作。您的期望可能需要调整一点点,但是。

Your code works correctly. Your expectations might need a little bit of adjusting, however.

FMOD 函数总是返回精确的结果---当你写 C = FMOD(A,B) C 是一个数字,这样ç+ K * b (无限precision计算)恰好等于 A 对于某个整数 K 。所以,你的code实际上是声音--- 如果(C == 0)将触发什么时候 A 正是A b 的倍数。

The fmod function always returns an exact result---when you write c = fmod(a, b), c is a number such that c + k*b (evaluated in infinite precision) exactly equals a for some integer k. So your code is actually sound---if (c == 0) will trigger exactly when a is exactly a multiple of b.

您把 B 双击 0.1 ,这实际上是分数36028797018963968分之3602879701896397,而不是分数 1/10 。所以,如果我计算 FMOD(1,0.1),我应该会得到分数(36028797018963968%3602879701896397)/ 36028797018963968 ,这是 3602879701896395 36028797018963968 。这是非常略小于双击名为 0.1

You took b to be the double 0.1, which is actually the fraction 3602879701896397/36028797018963968, not the fraction 1/10. So if I compute fmod(1, 0.1), I should expect to get the fraction (36028797018963968 % 3602879701896397) / 36028797018963968, which is 3602879701896395 36028797018963968. That's very slightly smaller than the double called 0.1.

这也解释了为什么当您使用code符合您的期望 0.25 而不是 0.1 ; 0.25 给你确切的1/4。

This also explains why your code meets your expectations when you use 0.25 instead of 0.1; 0.25 gives you 1/4 exactly.

您可以阅读这浮点指南了解浮动的重新presentation - 点号。

You might read this floating-point guide to learn about the representation of floating-point numbers.

这篇关于Ç - 比较花车if语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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