gpt4 book ai didi

c - 在 C 中,为什么比率 10.0/100 不同于 0.1?

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

<分区>

这是一个简单的问题,我搜索了论坛,但找不到答案(我找到了一个关于 Log 的答案,但我认为这里没有舍入误差)。

我编写了一个程序来确定一系列过期产品的罚款金额,但是当比率准确时,程序将返回下一个罚款类别,忽略条件中的 = 符号。

程序必须返回以下罚款:

  • 如果没有产品过期则为 0。
  • 如果最多 10% 的产品已过期,则为 100。
  • 如果超过 10% 的产品和最多 30% 的产品已过期,则为 10000。
  • 如果超过 30% 的产品已过期,则为 100000。

这是我写的代码:

#include <stdio.h>
int calculate_fine(int ncheckedproducts, int nexpiredproducts)
{
int fine;
float ratio;
ratio=(float)nexpiredproducts/ncheckedproducts;

if(nexpiredproducts==0)
fine=0;
else

if(ratio<=0.1)
fine=100;
else

if(ratio<=0.3)
fine=10000;
else
fine=100000;

return fine;
}

int main(void)
{
int ncheckedproducts, nexpiredproducts, fine;
printf("Type number of checked and expired products\n");
scanf("%d %d", &ncheckedproducts, &nexpiredproducts);
fine=calculate_fine(ncheckedproducts, nexpiredproducts);
printf("The fine is: %d\n", fine);
return 0;
}

但是对于值 100 和 10,以及 100 和 30,分别正好是过期产品的 10% 和 30%,程序将返回错误的罚款。

老师没有给我解释原因,并纠正了我以下功能:

int calculate_fine(int ncheckedproducts, int nexpiredproducts)
{
int fine;

if(nexpiredproducts==0)
fine=0;
else

if(nexpiredproducts<=0.1*ncheckedproducts)
fine=100;
else

if(nexpiredproducts<=0.3*ncheckedproducts)
fine=10000;
else
fine=100000;

return fine;
}

但是,我想知道为什么前 10% 的比率大于 0.1,以及为什么我不能使用这种方法。

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