gpt4 book ai didi

Cash.c 预计 18/n 而不是 22/n

转载 作者:行者123 更新时间:2023-11-30 21:05:43 24 4
gpt4 key购买 nike

我似乎无法弄清楚我的代码出了什么问题,但我收到的简单输入(如 1 或 2)的值不正确,但收到的 0.41 的输入正确。如果有人可以帮助我,我将不胜感激!

这是我的代码:

#include <stdio.h>
#include <cs50.h>
#include <math.h>
int main(void)

{
//Establish Variables
float amount_owed;
int c = 0;
//Get Valid Input from User
do
{
amount_owed = get_float ("Change Owed: ");
} while (amount_owed <= 0);

//Check for quarters, mark # of quarters that can be used, subtract value from original amount_owed
do
{
(c++);
(amount_owed = amount_owed - .25);
} while (amount_owed >= .25);

//Check for dimes, mark # of dimes that can be used, subtract value from original amount_owed

do
{
(c++);
(amount_owed = amount_owed - .1);
} while ((amount_owed >= .1) && (amount_owed < .25));

//Check for Nickels, mark $ of nickels that can be used, subtract value from original amount_owed

do
{
(c++);
(amount_owed = amount_owed - .05);
} while ((amount_owed >= .05) && (amount_owed < .1));

//Check for Pennies, mark # of pennis that can be used, subtract value from original amount_owed

do
{
(c++);
(amount_owed = amount_owed - .01);
} while ((amount_owed >= .01) && (amount_owed < .05));
//Print Number of Minimum number of coins that can be used

{
if (amount_owed == 0)
;
printf("%d\n", c);
}
}

最佳答案

首先,您永远不应该将 float 用于需要准确的内容。但让我们稍后再讨论这个问题,因为您的程序还存在另一个问题。

现在假设 float 实际上是精确的。

当你写下:

do
{
c++;
...
} while(...);

正文中的代码将始终执行至少一次

因此,对于您的代码,如果输入为 1.0,则第一个循环将执行 4 次,并且 amount_owed 将为 0.0

在接下来的 3 个 do-while 中,您仍然会进入正文一次并执行 c++(即使 amount_owed 为零) )。因此,结果将是 7 而不是 4(第一个循环中的 4 + 以下三个循环中的每一个循环中的 1)。

解决方案是使用常规的 while 而不是 do-while。喜欢:

#include <stdio.h>

int main(void) {
float amount_owed = 1.0;
int c = 0;

while (amount_owed >= 0.25)
{
c++;
amount_owed = amount_owed - 0.25;
}

while ((amount_owed - 0.1) >= 0)
{
c++;
amount_owed = amount_owed - 0.1;
}

while (amount_owed >= .05)
{
c++;
amount_owed = amount_owed - .05;
}

while (amount_owed >= .01)
{
c++;
amount_owed = amount_owed - .01;
}

printf("%d\n", c);

return 0;
}

回到使用浮点:浮点不能100%准确地表示每个数字。因此,在进行涉及 float 的计算时,您可能会看到一些舍入错误。因此,对于任何需要准确结果的计算,您应该尝试使用整数来完成。

对于这样的任务,“技巧”是将amount_owed视为您拥有的最低硬币的单位。通常,这意味着是“正常”思考方式的 100 倍。例如,您使用 117 而不是 1.17

那么你的代码可能更像是:

#include <stdio.h>

int main(void) {
unsigned amount_owed = 100; // note 100 instead of 1.0
int c = 0;

while (amount_owed >= 25) // note 25 instead of .25
{
c++;
amount_owed = amount_owed - 25;
}

while ((amount_owed - 10) >= 0)
{
c++;
amount_owed = amount_owed - 10;
}

. . .

关于Cash.c 预计 18/n 而不是 22/n,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53147814/

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