C++可能的硬币组合使用while循环
C++ possible coin combinations using while loop
我在编程课上遇到了一个挑战,我们必须使用 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;
}
}
现在我的问题是当我运行程序时,它会为四分之一、一角硬币和镍币返回一个非常大的负值。我肯定这与我的循环条件的设置方式有关,有人知道为什么会发生这种情况吗?
两个问题:一个未定义的硬币初始值。两个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
用于数量。
当我读到你的问题时,你似乎应该寻找一种方法来获得所有可能的组合。 奥利弗·马修斯(Oliver Matthews)的回答处理了第一部分(计算出您可以在更改中容纳多少给定类型的硬币),但是您必须在检查各种其他组合的循环中执行此操作(例如所有便士,所有硬币w/便士,所有硬币w/便士,所有四分之一w/便士等),并且需要一种方法来返回组合(例如,返回处理硬币的某个结构/类的向量通过输出参数计数 - 即按引用的向量)。
相关文章:
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- while循环中while循环的时间复杂度是多少
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- 擦除while循环中迭代的元素
- 为什么我不能在 while 循环中创建线程?
- 退出简单while循环时出现问题
- 如果条件为TRUE(最佳方式?),则在do while循环中后置增量
- 即使没有满足他们的条件,我也无法通过一些 do-while 循环
- 嵌套While循环不起作用(C++问题)
- 如何通过替换顺序代码的while循环来添加OpenMP for循环
- 使用 GMP 的 while 循环出现问题
- 程序以使用 C++ 中的 while 循环查找一组数字的最小值
- 为什么在 while 循环中返回表达式不起作用
- 如何使用 do while 循环确定最高值和最低值
- 如何读取单个字符并在输入两个字符序列时输出? 使用 while 循环和C++
- 用于在 C++ 中使用 while 循环查找下一个素数的简单函数
- OpenCV QT,显示视频的帧(不使用while循环)
- 在 while 循环中使用 pow() 函数 C++
- C++ 制作/命名不初始化的向量(在 while 循环中)
- std::getline没有在while循环中重新请求用户输入