C++ possible coin combinations using while loop -
i have challenge in programming class have use void function calculate possible coin combinations given change value 1 99 cents.
so far code looks this:
#include <iostream> using namespace std; void computecoins(int coinvalue, int& num, int& amount_left); int main() { //define varibles user input change int leftover, quarters=0, dimes=0, nickels=0, pennies=0, coins=0, originalamount; { cout << "enter change amount: "; cin >> originalamount; leftover = originalamount; } while ((leftover > 99) || (leftover < 1)); //larger 99 or smaller 1? if yes, 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 given " << quarters << " quarter/s, " << dimes << " dime/s, " << nickels << " nickel/s, " << " , " << pennies << " pennies."; cout << endl; system("pause"); return 0; } void computecoins(int coinvalue, int& num, int& amount_left) { //using specified coin value, find how many can go subtract while (amount_left % coinvalue == 0) { // still dividable coin value num += 1; amount_left -= coinvalue; } } now problem when run program, returns large negative value quarters, dimes, , nickels. i'm positive has how loop conditions set up, have idea why happening?
two issues: 1 undefined coins initial value. 2 amount_left % coinvalue == 0 part - think mean amount_left >= coinvalue
although there no need keep iterating in function
void computecoins(int coinvalue, int& num, int& amount_left) { // add many coinvalues possible. num += amount_left / coinvalue; // modulus must left. amount_left = amount_left % coinvalue; } note (among other things), you'd better off using unsigned ints quantities of things.
Comments
Post a Comment