gpt4 book ai didi

将货币值作为 float 进行比较不起作用

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

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

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

最佳答案

What is the most effective way for float and double comparison?

你应该使用这样的东西

bool isEqual(double a, double b)
{
return fabs(a - b) < EPSILON;
}

或者这个

#define ISEQUAL(a,b) ( fabs((a) - (b)) < EPSILON)

并定义EPSILON

#define EPSILON (0.000001)

关于将货币值作为 float 进行比较不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22126459/

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