gpt4 book ai didi

C - 比较 float 和 if 语句

转载 作者:太空宇宙 更新时间:2023-11-04 08:29:24 24 4
gpt4 key购买 nike

<分区>

我目前正在编写一个贪心算法,但我在比较 float 时偶然发现了一个问题。

我会使用这样的代码:

float f = 0;   

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

我已经在一个单独的程序上对此进行了测试,它运行良好,但在我正在处理的程序上却没有。

这是我自己的程序的摘录。

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;
}

奇怪的是,这似乎与之前的 if 语句一起工作,该语句检查用户输入的 fmod 何时为 0.25。

有没有更好的方法来检查一个 float 是否等于另一个 float ?

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com