gpt4 book ai didi

c - 为什么我的程序在某些测试中可以正常工作,而在其他测试中却不能正常工作?

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

这是我的测试的输出:

:) greedy exists

:) greedy compiles

:( input of 0.41 yields output of 4
expected "4\n", not "3\n"

:( input of 0.01 yields output of 1
expected "1\n", not "0\n"

:) input of 0.15 yields output of 2

:) input of 1.6 yields output of 7

:) input of 23 yields output of 92

:) input of 4.2 yields output of 18

:) rejects a negative input like -.1

:) rejects a non-numeric input of "foo"

:) rejects a non-numeric input of ""

这是代码:

#include <stdio.h>
#include <cs50.h>

void count_coins();

int coin = 0;
float change = 0;

int main(void)
{
do
{
change = get_float("How much change is owed? ");
}
while (change < 0);

count_coins();

printf("%i\n", coin);
}

void count_coins()
{
while (change > 0.24)
{
coin++;
change -= 0.25;
// printf("%.2f\n", change);
}

while (change > 0.09)
{
coin++;
change -= 0.10;
// printf("%.2f\n", change);
}

while(change > 0.04)
{
coin++;
change -= 0.05;
// printf("%.2f\n", change);
}

while (change >= 0.01)
{
coin++;
change -= 0.01;
// printf("%.2f\n", change);
}
}

最佳答案

正如 Havenard 已经写的那样,问题在于 change 存储为 float。对于这样的程序,更改必须存储为整数值。

这是您的代码,使用 int 而不是 float:

#include <stdio.h>
#include <cs50.h>

void count_coins (void);

int coin = 0;
int change = 0;

int main (void) {
do {
change = 41; // insert a get integer function here
} while (change < 0);

count_coins();

printf("%i\n", coin);
}

void count_coins (void) {
while (change >= 25) {
coin++;
change -= 25;
}

while (change >= 10) {
coin++;
change -= 10;
}

while(change >= 5) {
coin++;
change -= 5;
}

while (change >= 1) {
coin++;
change -= 1;
}
}

关于c - 为什么我的程序在某些测试中可以正常工作,而在其他测试中却不能正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46411952/

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