gpt4 book ai didi

c - 我的代码有什么问题(CS50 2012 Pset 1 贪婪)

转载 作者:行者123 更新时间:2023-11-30 18:26:21 28 4
gpt4 key购买 nike

我正在尝试制作一个程序,提供最少数量的硬币找零,但如果我给出的数字不是可分为四等分的数字,它就会惨败。例如,如果我输入 1.25,我会得到 5 个 25 美分,但如果我输入 1.26,我会得到 5 个 25 分 1 镍币,这当然是不正确的。我做错了什么?

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

void calculate_change(change_requested){
int num_quarters = 0;
int num_dimes = 0;
int num_nickles = 0;
int num_pennies = 0;

int val_quarters = 25;
int val_dimes = 10;
int val_nickles = 5;

num_quarters = floor(change_requested/val_quarters);
if(change_requested % val_quarters != 0){
num_dimes = floor( (change_requested - (num_quarters * val_quarters))/val_dimes );
if( change_requested - (((num_quarters * val_quarters) + (num_dimes * val_dimes))) != 0){
num_nickles = floor( change_requested - ( (num_quarters * val_quarters) + (num_dimes * val_dimes)/val_nickles ));
if( change_requested - (((num_quarters * val_quarters) + (num_dimes * val_dimes) + (num_nickles * val_nickles))) != 0){
for(int i = 0; i<change_requested - (((num_quarters * val_quarters) + (num_dimes * val_dimes) + (num_nickles * val_nickles))); i++){
num_pennies++;
}
}
}
}
if(num_quarters > 0){
printf("%i Quarters ",num_quarters);
}
if(num_dimes > 0){
printf("%i Dimes ",num_dimes);
}
if(num_nickles > 0){
printf("%i Nickles",num_nickles);
}
if(num_pennies > 0){
printf("%i Pennies",num_pennies);
}
printf("\n");

}

int main (void){
printf("How Much Change Do You Need?\nAmount: ");
float change_requested = GetFloat();
calculate_change(change_requested * 100);
return 0;
}

最佳答案

我觉得你把这件事搞得太复杂了。如果需要写

for(int i = 0; i<change_requested - (((num_quarters * val_quarters) + (num_dimes * val_dimes) + (num_nickles * val_nickles))); i++){

所有这些都在一行中,那么肯定出了问题。您可以用更简单的方法来做到这一点,通过从总量中减去刚刚计算出的硬币的值(value)来获得剩余的:

int vals[] = { 25, 10, 5 };
const char *names[] = { "quarters", "dimes", "nickles" };

int pennies = 100 * GetFloat(); // not good at all, btw (*)

for (int i = 0; i < 3; i++) {
int n = pennies / vals[i];

if (n) {
printf("%d %s ", n, names[i]);
}

pennies -= n * vals[i];
}

if (pennies)
printf("%d pennies", pennies);

printf("\n");

至于为什么 GetFloat() 不好: float 并不精确,因此,例如,1.26 实际上可能表示为 1.25999946 之类的东西。当你把它转换成整数值时,运气不好的话可能会因为截断而损失一分钱左右。

关于c - 我的代码有什么问题(CS50 2012 Pset 1 贪婪),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17985412/

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