gpt4 book ai didi

c - 贪心硬币计数中的整数溢出

转载 作者:太空宇宙 更新时间:2023-11-04 00:45:43 25 4
gpt4 key购买 nike

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

int main (void) {

printf ("Enter amount: ");
float amount = GetFloat();
int coins = 0;

while (amount != 0) {

if (fmod(amount, 0.25) == 0) {
amount = amount - 0.25;
coins += 1;
}

else if (fmod(amount, 0.10) == 0) {
amount = amount - 0.10;
coins += 1;
}

else if (fmod(amount, 0.05) == 0) {
amount = amount - 0.05;
coins += 1;
}

else {
amount = amount - 0.01;
coins += 1;
}
}

printf ("Coins : %d\n", coins);
}

我正在尝试实现一个小的贪心算法,在该算法中,用户输入一定数量的钱(例如:9.25),然后我们输出最少的硬币来兑换零钱(25 美分,仅 10 美分、5 美分和 1 美分)。

此算法适用于 10 或 20 等整数,以及仅要求程序使用 25 美分硬币的金额。

如果我尝试像 9.10 或 9.01 这样的数量,我会收到运行时错误,有符号整数溢出。我明白这意味着什么,但我不明白为什么币值会一下子涨那么高。

最佳答案

正如 Danial Tran 所说,在进行逻辑运算时最好使用 int。请阅读Why not use Double or Float to represent currency?您也可以避免 while 循环。

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

int main (void) {

printf ("Enter amount: ");
//float amount = GetFloat(); //Please refer to chqrlie's comments below.
double amount = 0.0;
scanf("%lf",&amount); //I don't know GetFloat() equivalent for double. So using scanf().

long long int amountInt = (long long int) (amount * 100.0);

int coins = 0;

if (25 <= amountInt) {
coins += (amountInt/25);
amountInt = amountInt % 25;
}

if (10 <= amountInt) {
coins += (amountInt/10);
amountInt = amountInt % 10;
}

if (5 <= amountInt) {
coins += (amountInt/5);
amountInt = amountInt % 5;
}

if (1 <= amountInt) {
coins += amountInt;
}

printf ("Coins : %d\n", coins);
}

关于c - 贪心硬币计数中的整数溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40765164/

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