gpt4 book ai didi

c - 这段代码有一个错误

转载 作者:行者123 更新时间:2023-11-30 21:23:19 25 4
gpt4 key购买 nike

我是 this online judge 的初级问题解决者。我在前 20 个问题中做得很好。但在没有。 21我被困。我写了这段代码:

#include <stdio.h>
#include <math.h>
int main()
{
double notes[] = {100, 50, 20, 10, 5, 2};
double moedas[] = {1, 0.50, 0.25, 0.10, 0.05, 0.01};
int amount_of_notes[6];
int amount_of_moedas[6];
double n, x;
int i, j;
scanf("%lf", &n);
printf("NOTAS: \n");
for(i = 0; i < 6; i++)
{
x = fmod(n, notes[i]);
amount_of_notes[i] = n/notes[i];
n = x;
printf("%d nota(s) de R$ %.2lf\n", amount_of_notes[i], notes[i]);
}
printf("MOEDAS: \n");
for(j = 0; j < 6; j++)
{
amount_of_moedas[j] = n/moedas[j];
x = fmod(n, moedas[j]);
n = x;
printf("%d moeda(s) de R$ %.2lf\n", amount_of_moedas[j], moedas[j]);
}
return 0;
}

此代码采用 C 语言编写。此代码将数字转换为一些纸币和硬币。但是当我输入 54.54 时,输出如下:

NOTAS: 
0 nota(s) de R$ 100.00
1 nota(s) de R$ 50.00
0 nota(s) de R$ 20.00
0 nota(s) de R$ 10.00
0 nota(s) de R$ 5.00
2 nota(s) de R$ 2.00
MOEDAS:
0 moeda(s) de R$ 1.00
1 moeda(s) de R$ 0.50
0 moeda(s) de R$ 0.25
0 moeda(s) de R$ 0.10
0 moeda(s) de R$ 0.05
3 moeda(s) de R$ 0.01

正如您所看到的,在最后一行中,只有 3 显示了它应该显示 4 的位置。我非常努力地寻找代码中的错误。我失败了。请帮忙找出这段代码的bug!!

最佳答案

对于任何需要精度的东西,避免使用浮点变量。浮点不精确,您将面临舍入错误。在您的例子中,您期望 4,但由于舍入错误而得到 3。

而是使用整数进行所有计算并使用分作为基本单位。

类似于:

#include <stdio.h>
#include <math.h>
int main()
{
int notes[] = {10000, 5000, 2000, 1000, 500, 200}; // Unit is cents
int moedas[] = {100, 50, 25, 10, 5, 1}; // Unit is cents
int amount_of_notes[6];
int amount_of_moedas[6];
double n;
int x;
int n_int;
int i, j;
scanf("%lf", &n);
n_int = 100 * n; // Unit is cents
printf("NOTAS: \n");
for(i = 0; i < 6; i++)
{
x = n_int / notes[i];
amount_of_notes[i] = x;
n_int -= x * notes[i];
printf("%d nota(s) de R$ %.2lf\n", amount_of_notes[i], notes[i]/100.0);
}
printf("MOEDAS: \n");
for(j = 0; j < 6; j++)
{
x = n_int / moedas[j];
amount_of_moedas[j] = x;
n_int -= x * moedas[j];
printf("%d moeda(s) de R$ %.2lf\n", amount_of_moedas[j], moedas[j]/100.0);
}
return 0;
}

输入:

54.54

输出:

NOTAS: 
0 nota(s) de R$ 100.00
1 nota(s) de R$ 50.00
0 nota(s) de R$ 20.00
0 nota(s) de R$ 10.00
0 nota(s) de R$ 5.00
2 nota(s) de R$ 2.00
MOEDAS:
0 moeda(s) de R$ 1.00
1 moeda(s) de R$ 0.50
0 moeda(s) de R$ 0.25
0 moeda(s) de R$ 0.10
0 moeda(s) de R$ 0.05
4 moeda(s) de R$ 0.01

关于c - 这段代码有一个错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46531872/

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