gpt4 book ai didi

使用 while 循环的 C++ 可能的硬币组合

转载 作者:行者123 更新时间:2023-11-28 03:07:56 24 4
gpt4 key购买 nike

我在编程课上遇到了一个挑战,我们必须使用一个 void 函数来计算可能的硬币组合,给定的变化值从 1 到 99 美分。

到目前为止,我的代码如下所示:

    #include <iostream>

using namespace std;

void computeCoins(int coinValue, int& num, int& amount_left);

int main()
{
//Define varibles then get user input for change
int leftOver, quarters=0, dimes=0, nickels=0, pennies=0, coins=0, originalAmount;
do
{
cout << "Enter change amount: ";
cin >> originalAmount;
leftOver = originalAmount;
} while ((leftOver > 99) || (leftOver < 1)); //Larger than 99 or smaller than 1? If yes, then try again.

//Quarters
computeCoins(25, coins, leftOver);
quarters = coins;

//Dimes
computeCoins(10, coins, leftOver);
dimes = coins;

//Nickels
computeCoins(5, coins, leftOver);
nickels = coins;
pennies = leftOver;

cout << originalAmount << " cent/s could be given as " << quarters << " quarter/s, " << dimes << " dime/s, " << nickels << " nickel/s, " << " and " << pennies << " pennies.";
cout << endl;
system("PAUSE");
return 0;
}

void computeCoins(int coinValue, int& num, int& amount_left)
{
//Using the specified coin value, find how many can go into it then subtract it
while (amount_left % coinValue == 0)
{
// Still dividable by the coin value
num += 1;
amount_left -= coinValue;
}
}

现在我的问题是,当我运行该程序时,它会为 25 美分、10 美分和 5 分硬币返回一个非常大的负值。我肯定这与我的循环条件的设置方式有关,有人知道为什么会这样吗?

最佳答案

两个问题:一是未定义硬币初始值。两个 amount_left % coinValue == 0 部分 - 我想你的意思是 amount_left >= coinValue

虽然没有必要一直在那个函数里迭代

void computeCoins(int coinValue, int& num, int& amount_left)
{
// add as many coinValues as possible.
num += amount_left / coinValue;
// the modulus must be what is left.
amount_left = amount_left % coinValue;
}

请注意(除其他事项外),您最好使用 unsigned ints 来表示数量。

关于使用 while 循环的 C++ 可能的硬币组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19228181/

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