C++ possible coin combinations using while loop - c++

I have a challenge in my programming class where we have to use a void function to calculate the possible coin combinations with a given change value from 1 to 99 cents.
So far my code looks like this:
#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;
}
}
Now my problem is when I run the program, it returns a very large negative value for quarters, dimes, and nickels. I'm positive it has something to do with how my loop conditions are set up, does anyone have an idea why this is happening?

Two issues: one undefined coins initial value. Two the amount_left % coinValue == 0 part - I think you mean amount_left >= coinValue
Although there is no need to keep iterating in that function
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;
}
Note that (among other things), you'd be better off using unsigned ints for quantities of things.

As I read your question, it appears you are supposed to look for a way to get all possible combinations. Oliver Matthews' answer handles the first part of that (figuring out how many of a given type of coin you can fit in the change), but you'd have to do that in a loop that checks various other combinations (e.g. all pennies, all nickels w/pennies, all dimes w/pennies, all quarters w/pennies, etc.) and need a method for returning the combinations (e.g. return a vector of some structure/class that handles the coin counts through an output parameter - that is, a vector by reference).

Related

Console not printing expected output

I am trying to expand on previous code by implementing 2D-array's, however I keep getting issues with the console not outputting the correct values. The console is not taking in the right values when calculating the average and outputs 0 instead of the expected value. When running the code, the section where it would display the High and the Low scores would always display the first number that was typed in.
There are restrictions to work under.
Adjust the logic to drop the high score and the low score and average the remaining three scores for each student. The student grade is based on the average of the 3 middle scores.
All data is read in from the keyboard.
Two global constants may be utilized: one for the number of students and one for the number of tests.
Display in a table format the student's name, 5 test scores, average, and grade. Include a header in the table to label each column respectively.
Use iomanip and setw() to format the output.
Main should consist of variable declarations and function calls. This means the for loops to process the arrays resides in the functions, not in main.
Has to follow the base code.
`
using namespace std;
const int SCORES = 5;
const int NUM_STUDENTS = 3;
int main()
{
string name[NUM_STUDENTS];
int test[NUM_STUDENTS][SCORES];
char grade[NUM_STUDENTS];
float avg{};
int total = 0;
int hiIndex{}, loIndex{};
calcData(name, test, grade, total, hiIndex, loIndex, avg);
//display results
displayResults(name, test, grade, avg, loIndex, hiIndex);
system("pause");
return 0;
}
void calcData(string name[], int test[][SCORES], char grade[], int total, int hiIndex, int loIndex, float& avg)
{
for (int counter = 0; counter < NUM_STUDENTS; counter++)
{
getInput(name, test, counter, total);
cin.ignore();
//find index of the highest score and lowest score
findHiAndLow(test, hiIndex, loIndex, counter);
//assign letter grade
assignGrade(avg, grade, counter);
//calculate the class average
calcAvg(total - (test[counter][hiIndex] + test[counter][loIndex]), avg, SCORES - 2);
}
}
void getInput(string arrOne[], int arrTwo[][SCORES], int size, int& t)
{
//get student name
cout << "Input the student name and press enter\n";
getline(cin, arrOne[size]);
for (int i = 0; i < SCORES; i++)
{
//get student test score
cout << "Input the score for the midterm test\n";
cin >> arrTwo[size][i];
//(accumulate scores) total of all scores
t += arrTwo[size][i];
}
cout << endl;
}
int findHiAndLow(int t[][SCORES], int& h, int& l, int row)
{
for (int i = 0; i < SCORES; i++)
{
if (t[row][h] < t[row][i])
h = row;
if (t[row][l] > t[row][i])
l = row;
}
return h, l;
}
float calcAvg(int t, float a, int size)
{
a = static_cast<float>(t) / size;
return a;
}
void displayResults(string n[], int t[][SCORES], char g[], float a, int low, int high)
{
for (int counter = 0; counter < NUM_STUDENTS; counter++)
{
cout << left << setw(10) << n[counter] << ":";
for (int i = 0; i < SCORES; i++)
{
cout << setw(10) << t[counter][i];
}
cout << endl;
}
cout << "\n\nThe class average for this test = " << a << endl << endl;
for (int i = 0; i < NUM_STUDENTS; i++)
{
cout << n[i] << " your highest test score = " << t[i][high] << endl;
cout << n[i] << " your lowest test score = " << t[i][low] << endl << endl;
}
}
`
The expected outcome was for the program to take the average of the 3 middle scores that are left after dropping both the high and low scores from the initial 5 scores that are given. I have tried rearranging the values in both findHiandLow() and getInput(). I have tried having both for loops for getInput() within the function and have switched back to having one on the outside (within calcData()) to include the other functions, with the intent of having it loop for each student.
I wanted the console to print out the average of the three middle scores and not include the High and low, I was also expecting the console to print out the High and low scores for the student but it only prints the first score.
If my numbers were, for example, 12, 89, 45, 100, 23; The expectation would've been that it would drop the 12 and 100 and leave me with 89, 45, and 23. It would then take the average of those 3 numbers which in theory should result in 52.34 and result in an "F", however it prints out 0. and because the number that was first typed in was 12 the lowest and highest number would be listed as 12. It should have been 12 and 100 respectively.
This is another case of the incredibly common newbie confusion over returning values from functions.
This is your function
float calcAvg(int t, float a, int size)
{
a = static_cast<float>(t) / size;
return a;
}
You are trying to calculate the average and return the result, but for some reason you have declared a as a parameter, instead of as a local variable. This is how it should look
float calcAvg(int t, int size)
{
float a = static_cast<float>(t) / size;
return a;
}
Once you see that you should see that it can be further simplified, eliminating a altogether
float calcAvg(int t, int size)
{
return static_cast<float>(t) / size;
}
Now look at how you call calcAvg.
calcAvg(total - (test[counter][hiIndex] + test[counter][loIndex]),
avg, SCORES - 2);
you are calling the function, but doing nothing with the returned value. This is how it should look
avg = calcAvg(total - (test[counter][hiIndex] + test[counter][loIndex]),
SCORES - 2);
Now the return value of calcAvg is being assigned to the variable avg changing it's value. This is clearly what you intended. If you want to change the value of a variable using a functions return value the syntax is x = func(); not func(x).
Really not sure why this is such a stumbling block for newbies. The correct code has always seemed natural and straightforward to me. But, in any case, remember that parameters and return values are different things, with different syntax, and different purposes.

C++ Finding square root without sqrt function loop glitching

So I am making this as a homework assignment. I understand that there are so many ways that this code could be more efficient and accurate but this is the way my professor wants it done.
I am having problems with the loop. When I ask for the square root of 67 it does find it but it loops the correct answer 3 times.
Enter a value to be square rooted:
67
33.5
guess = 17.75
guess = 10.7623
guess = 8.49387
guess = 8.19096
guess = 8.18535
guess = 8.18535
guess = 8.18535
The program took 7 guess to find an estimation.
When I try to find the square root of 5 it finds it but continues to loop indefinitely
using namespace std;
int main()
{
double guess2;
double squarenumber;
double guess1;
int numofguess = 0;
cout << "Enter a value to be square rooted: " << endl;
cin >> squarenumber;
guess1 = squarenumber/2;
cout << guess1 << endl;
do
{
guess2 = (guess1 - (((guess1 * guess1) - squarenumber)/(2* guess1)));
guess1 = guess2;
cout << "guess = " << guess2 << endl;
numofguess = numofguess + 1;
} while ((guess2 * guess2) > squarenumber);
cout<< "The program took "<< numofguess <<" guess to find an estimation.";
return 0;
}
I think that what you are missing is a proper exit condition.
Your code is written to loop indefinitely until the guess is "perfect".
You should have an exit condition checking if current guess is the same as previous guess, which obviously means that you won't do any better.
Here is my suggestion based on your code :
using namespace std;
int main()
{
double guess2;
double squarenumber;
double guess1;
int numofguess = 0;
cout << "Enter a value to be square rooted: " << endl;
cin >> squarenumber;
guess2 = guess1 = squarenumber/2;
cout << guess1 << endl;
const double epsilon = squarenumber * 1E-6;
do
{
guess1 = guess2;
guess2 = (guess1 - (((guess1 * guess1) - squarenumber)/(2* guess1)));
cout << "guess = " << guess2 << endl;
numofguess = numofguess + 1;
} while ((guess2 * guess2) > squarenumber && fabs(guess2-guess1) > epsilon);
cout<< "The program took "<< numofguess <<" guess to find an estimation.";
return 0;
}
Mickaël C. Guimarães's answer is basically correct, check for an episolon value (absolute difference from the correct answer and your answer). But the "(guess2 * guess2) > squarenumber" should be dropped completely. That's because the value could in theory overshoot and be too low. The algorithm actually goes upwards if the value is too low. e.g. if you want SQRT(25) and your "guess1" prediction is way too low at 2, then guess2 would equal
(2 - (((2 * 2) - 25)/(2* 2))) = 7.25;
And on the next iteration then falls to 6.725624, so heads in the right direction. Low values actually get boosted up and eventually approach the target. By stopping if the value drops below the true SQRT then you might get "false positives" where too low values are accepted as accurate enough.
The times when the system got "stuck" were basically like the story Acchiles and the Tortoise. At each step, the system was dividing the remaining distance to go by some amount, but the change was therefore smaller each step, and could in theory never converge on the exact value, therefore you decide how much accuracy you want so that it finishes in a set time.
Additionally, the issue where the system seemed to take too many steps to converge is because floating point numbers are stored in higher precision, but cout has limited display precision. You can control that by sending setting values to cout before the print commands:
std::cout << std::fixed; // force all values to show to the same decimals
std::cout << std::setprecision(6); // set how many places to show
These code can be streamed to cout in one command before the value to print as well:
std::cout << std::fixed << std::setprecision(6) << "guess = " << guess2 << endl;

Issue with calling function that takes in three parameters, one being int const [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm posting because I'm having issues figuring out why my "total aid available" is not printing the total of the pell grant, stafford loan, and work-study loan. I've tried fixing my function again and again (I used sources online and in reference book, but I don't know if the issue is that my function won't be called or not, since nothing is printing for the total aid available.
Everything else is fine, except that one thing, and it is really bugging me since no matter what changes I make, I'm in the same state. No errors showing either. I'm using microsoft visual studio for the first time as compiler, so I wonder if that is the issue.
Here is what I have:
#include <iostream>
using namespace std;
double pell_Grant(double); // forward declaration on pell_Grant ( which is a function for calculating pell grant)
double sum(double, int const, double); // declaration for sum function which gives total for the total aid available
int main()
{
double workstudy = 0, pellgrant = 5730, grossincome = 0, Total = 0; // variables
int yes;
int const stafford = 9500; //const declaration
cout << "Lemme Forecast Your FAFSA" << endl;
cout << "Enter your adjusted gross income: " << endl; cin >> grossincome; // input for gross income
if (grossincome >= 30000) // if gross income is higher than 30,000 then print message
{
cout << "Sorry Charlie, your income is too high to run this forecaster!";
return 0;
}
cout << "Can someone claim you as a dependent? [1=yes/0=no]: " << endl; // input to claim dependent or not
cin >> yes;
if (yes == 1) // if 1 for yes is selected then pell grant gets reduced by 750, if 0 or no selected, then program goes by standard procedure
{
pellgrant -= 750;
}
workstudy = 1465; // work study must be nationwide avergae 1,465
if (grossincome >= 19000) // if this condition is met then work study is not met and message is printed as follows...
{
cout << "Your Work-Study Award is not available for your income level" << endl;
workstudy = 0;
}
double foo = pell_Grant(grossincome); // value returned from pell_Grant stored here to give total
Total = sum(workstudy + stafford + pellgrant); // sum function is called and stores result in Total
if (workstudy != 0) // if work study loan isn't more than 19,000 then it will be calculated and printed in next statement
{
cout << "Your Work-Study Award (if available)= " << workstudy << endl;
}
cout << "Your Stafford Loan award (if needed)= " << stafford << endl; // prints stafford loan (const called)
cout << "Your Pell Grant= " << pellgrant << endl; // prints pell grant
cout << "Total Aid Available For You=" << Total << endl; // prints total
return (0);
}
double pell_Grant(double x) // pell_Grant function that calculates pell grant which is assigned 5,730
{
// x is gross income which is assigned 5,730. This is money received that does not need to be repaid.
if ((x > 12000) && (x < 20000)) // statement makes sure adjusted gross is bettween 12000 & 20000
{
double a = x / 1000; // for every 1,000 in adjusted gross income... reduce/subtract 400 from it
a *= 400;
x -= a;
}
if (x > 20000) // check if gross income is more than 20000
{
double a = x / 1000; // for every 1,000 in gross income, subtract 500
a *= 500;
x -= a;
}
return x;
}
double sum(double workstudy , int const stafford, double pellgrant) // function for adding up workstudy loan, stafford loan, and pellgrant loan
{
double Total;
Total = workstudy + stafford + pellgrant;
return (Total); // returns total
}
According to its declaration, the method sum() accepts 3 parameters.
double sum(double, int const, double);
But while calling you are passing only 1 parameter:
Total = sum(workstudy + stafford + pellgrant);
Instead, you need to pass 3 parameters, like this:
Total = sum(workstudy, stafford, pellgrant);
But, I don't understand why you aren't getting any errors! You are trying to call a non-existent function. You must get a compiler error.
You are calling your sum() function incorrectly. This is your code:
Total = sum(workstudy + stafford + pellgrant); // sum function is called and stores result in Total
But your sum() function has three parameters. The correct form to call the function would be:
Total = sum(workstudy, stafford, pellgrant); // sum function is called and stores result in Total

C++ Functions and Passing Variables [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
C++ passing variables in from one Function to the Next.
The Program is working but when it comes to getUserData it asks for the same information 4 times and then displays the results with negative numbers. I used test numbers for number of rooms 1, 110 for sqrt feet in the room, 15.00 for cost of paint.
//Problems with this not working
void showMenu();
void getUserData(int &, double &, int &);
void doEstimate(int &, double &, int &, double &, double &);
void showReport();
int main()
{
int choice;
//I am not sure why I have to do this but someone suggested to do it and the program complied when I did this int calc ect
int calcGallonsOfPaint, rooms, totalsqrtfeet;
double calcCostOfPaint, costOfPaint;
int calcHoursOfLabor;
double calcLaborCost;
double calcPaintJobCost;
// Set up numeric output formatting.
cout << fixed << showpoint << setprecision(2);
do
{
// Display the menu and get the user's choice.
showMenu();
cin >> choice;
// Validate the menu selection.
while (choice < 1 || choice > 2)
{
cout << "Please enter 1 or 2: ";
cin >> choice;
}
if (choice == 1)
{
//for some reason it just keeps repeating the function getUserData
getUserData(rooms, costOfPaint, totalsqrtfeet);
doEstimate(calcGallonsOfPaint, calcCostOfPaint, calcHoursOfLabor, calcLaborCost, calcPaintJobCost);
showReport();
}
} while (choice != 2);
return 0;
}
void getUserData(int &rooms, double &costOfPaint, int &totalsqrtfeet)
{
int sqrtfeet;
int count = 0;
cout << "Please enter the number of rooms to be painted: ";
cin >> rooms;
cout << "Please enter square feet of wall space in each room: ";
cin >> sqrtfeet;
for (count = 1; count <= rooms; count++)
{
cout << "Please eneter square feet of wall space in room " << count << ": ";
cin >> sqrtfeet;
totalsqrtfeet += sqrtfeet;
}
cout << "What is the cost of the paint: ";
cin >> costOfPaint;
system("cls");
system("pause");
}
void doEstimate(int &calcGallonsOfPaint, double &calcCostOfPaint, int &calcHoursOfLabor, double &calcLaborCost, double &calcPaintJobCost)
{
//I am not sure why I have to do this but someone suggested to do it and the program complied when I did this: puting int rooms ect
int rooms, totalsqrtfeet;
double costOfPaint;
getUserData(rooms, costOfPaint, totalsqrtfeet);
calcGallonsOfPaint = 1 * (totalsqrtfeet/110); //Calculates the number of whole gallons of paint required.
calcCostOfPaint = calcGallonsOfPaint * costOfPaint; //Calculates the cost of the paint required.
calcHoursOfLabor = calcGallonsOfPaint * 6; //Calculates the number of whole hours of labor required.
calcLaborCost = calcHoursOfLabor * 15.00; //Calculates the labor charges.
//Calculates the cost of the paint job. This is the sum of the labor charges and the cost of the paint required.
calcPaintJobCost = calcLaborCost + calcCostOfPaint;
/*110 square feet of wall space
one gallon of paint
six hours of labor
$15.00 per hour for labor
*/
}
void showReport()
{
//I am not sure why I have to do this but someone suggested to do it and the program complied when I did this
int calcGallonsOfPaint, rooms, totalsqrtfeet;
double calcCostOfPaint, costOfPaint;
int calcHoursOfLabor;
double calcLaborCost;
double calcPaintJobCost;
getUserData(rooms, costOfPaint, totalsqrtfeet);
doEstimate(calcGallonsOfPaint, calcCostOfPaint, calcHoursOfLabor, calcLaborCost, calcPaintJobCost);
cout << "The number of rooms to be painted: " << rooms << endl;
cout << "The number of whole gallons of paint required: " << calcGallonsOfPaint << endl;
cout << "The hours of labor required: " << calcHoursOfLabor << endl;
cout << "The cost of the paint: " << calcCostOfPaint << endl;
cout << "The labor charges: " << calcLaborCost << endl;
cout << "The total cost of the paint job: " << calcPaintJobCost << endl;
system("pause");
system("cls");
}
One thing that you should do is initialise totalsqrtfeet to zero in your main function. That's because you're just adding the size of each room to it and it starts out with a random value: junk + a + b + c + d is still junk :-)
On top of that, you call getUserData from your main function and then again from doEstimate. And then you call them both again in showReport. That's why it's asking four times. Just call getUserData once. Since it's homework, I'll leave you to figure out where but here's a hint. If you do it in main (nudge, nudge, wink, wink), you'll have to pass he variables into doEstimate as well, not create new variables of the same name within that function and magically expect the compiler to associate them with the originals.
To caveat on what paxdiablo said, you are calling getUserData in your nested while loop, but I don't understand the purpose of calling getUserData(rooms, costOfPaint, totalsqrtfeet); prior to doEstimate(...) when the data isn't used nor passed to doEstimate(...) until you call getUserData again while inside the doEstimate(...) function. You should pass by value the rooms, costOfPaint, and totalsqrtfeet variables to doEstimate(...) or make them global since you only have one main() function anyways. If you had some sort of OO solution, then I wouldn't recommend making them global and rather part of a class.
Also all these variables are ZERO or NULL when they are passed into doEstimate(...):
calcGallonsOfPaint, calcCostOfPaint, calcHoursOfLabor, calcLaborCost, calcPaintJobCost
If you want to output them, then you need to pass them by reference to doEstimate(...) and then when it gets to the cout then it will sufficiently print the correct values. That is why it is zero.
The bottom line is though you need one function to call the other functions. That would be the simplest plan at this point, such as:
GetDataAndPrint(...) {
// Get some data
// Do estimate, pass in values by reference
// Print Results from calculated values
// return
}

C++ Perfect Number. Need some help revising

I need some help revising this. It keeps only displaying 0s as the temp. Thank you.
// A program to determine whether the input number is a perfect number
// A perfect number is defined by the sum of all its positive divisors excluding itself
// 28: 1+2+3+7+14 = 28.
int perfect, limit, divisor;
cout << "Please enter a positive integer in order to define whether it is a perfect integer or not: " ;
cin >> perfect;
cout << endl;
int temp = 0;
int prevtemp = 0;
limit = 1;
divisor = 1;
while (limit < perfect)
{
if ((perfect % divisor) == 0)
{
divisor = prevtemp;
temp = prevtemp + temp;
}
limit++;
divisor++;
}
if (perfect == temp)
cout << "Your number is a perfect number!" << endl;
else
cout << "Your number is not a perfect number" << endl;
return 0;
You are never setting prevtemp to anything other than 0, so adding it to temp does nothing.
I believe you meant to say
if ((perfect % divisor) == 0)
temp += divisor; // not "divisor = prevtemp;"
The line "temp = prevtemp + temp" should also be removed with this solution; there is no longer any need for the prevtemp variable.
Also, there is no need to keep separate limit and divisor variables, since they are always the same. Just remove limit and change the loop condition to use divisor.
Also, as Mark Byers pointed out, the loop would be simpler to understand if you refactored it into a for loop rather than a while.
It seems like you are making it too complicated. Here's how you could do it:
int total = 0;
for (int i = 1; i < perfect; ++i)
{
if (perfect % i == 0)
total += i;
}
if (perfect == total)
cout << "Your number is a perfect number!" << endl;
else
cout << "Your number is not a perfect number" << endl;
Note that the running total is kept in a variable called total (you called this variable temp) and it is only increased when the number is an exact divisor.
I'm not sure, but I'd guess that in the code:
if ((perfect % divisor) == 0)
divisor = prevtemp;
you intended this to be prevtemp=divisor instead. That fixes an obvious problem, but still leaves quite a bit that doesn't look like it's doing that you probably intended. For example, I can't quite figure out what limit is intended to accomplish -- you initialize it and increment it, but as far as I can see, you never use its value (well, I guess you use it, but its value is always the same as divisor's so I'm not sure why you think you need both, or how limit makes any sense as its name).
Edit: It would make sense to have a limit. In particular, factors always come in pairs: one that's less than or equal to the square root of the number, and one that matches the first that's always greater than or equal to the square root of the number. As such, you don't need to scan all the way up to the number itself looking for factors -- you can set the square root of the number as the limit, and scan only up to that point. For each factor you find up to that point, the matching factor will be perfect/divisor. Since you've already gotten one working example, I guess I might as well just hope this isn't homework, and post an example as well:
bool is_perfect(int number) {
int limit = sqrt((double)number);
int sum = 1;
for (int i=2; i<=limit; i++)
if (number % i == 0)
sum += i + number/i;
return sum == number;
}
You are never assigning anything to prevtemp after initializing it to 0, so there is nothing to add to temp on the line that reads temp = prevtemp + temp.
#include<iostream>
#include<iomanip>
using namespace std;
int main(){
int n,i=1,sum=0;
cout<<"Enter a number: ";
cin >> n;
while(i<n){
if(n%i==0)
sum=sum+i;
i++;
}
if(sum==n)
cout << i << " is a perfect number";
else
cout << i << " is not a perfect number";
system("pause");
return 0;
}