Coin machine regarding decimals - c++

Everything works as intended except one minor screwy line of code. The very last line that calculates the fee. For example if you type in 105 it says you entered $1.05, which is good, then it calculates the fee for the transaction which gives you $0.93555 as your take-home pay. I only want it to display up to the hundredths place no matter the dollar amount, not the hundred thousandth place. So it should display $0.93 because that's realistic. Note that depending on the integer you enter at the start, sometimes the decimal is placed correctly and sometimes the thousandth place is displayed, it's being screwy like that an I am not sure what to fix.
#include <iostream>
using namespace std;
int main() {
int cents;
double total;
cout<<"Enter total amount of coins (whole number): "; //Enter any whole number
cin>>total;
cents = total;
cout<<"You entered " << cents / 25 << " quarters";
cents = cents % 25;
cout<<", " << cents / 10 << " dimes";
cents = cents % 10;
cout<<", " << cents / 5 << " nickels";
cents = cents % 5;
cout<<", " << cents / 1 <<" pennies.";
cents = cents % 1;
cout<<" That is " << "$" <<total / 100 << "."<<endl; //Converting to dollar amount
cout<<"After the fee, you take home " << "$" << (total - (0.109 * total)) / 100 << "."; //What you're left with after the fee

You can use setprecision() if you include <iomanip> in the header and then use fixed to set how ever many digits you want to display after the decimal.
These pages explain it pretty well:
http://www.cplusplus.com/reference/ios/fixed/
http://www.cplusplus.com/reference/iomanip/setprecision/

In the last statement, the expression
(total - (0.109 * total)) / 100
should be:
(total - int(0.109 * total))/100
(In this case you can get away with not using <iomanip> or any other extras. Simply cast the product to int)

The bug:
The take home fee does not give only two decimals places. Example: Entering 105 coins give a take home fee of 0.93555.
Expected behavior:
The take home fee should be rounded down to two decimal place. (I assume "The Company" want more money. So they want round down the take home money. Every penny counts.)
Tracing the possible causes of the bug:
The take home fee is printed by the last line. So the last line may cause the bug.
The last line's formula ((total - (0.109 * total)) / 100) depends on the variable total.
Only the cin line (cin >> total;) and the definition of total (double total;) affects the variabletotal
These are all of the possible causes of the bug.
Simplified program that contains all possible causes of the bug:
#include <iostream>
using namespace std;
int main() {
double total;
// Enter any whole number
cout << "Enter total amount of coins (whole number): ";
cin >> total;
// What you're left with after the fee
cout << "After the fee, you take home " << "$"
<< (total - (0.109 * total)) / 100
<< ".";
}
Some ideas:
Idea 1: To round down a float number to integer, just cast it to integer. (e.g. cout << int(30.10) << "\n";)
Idea 2: Round down a float number to two decimal places is multiply the float number by 100, round down the result to integer, and then divide by 100.0.
If that sounds too tedious, can also use a library. see Rounding to 2 decimal points
A solution:
#include <iostream>
using namespace std;
int main() {
// Enter any whole number
cout << "Enter total amount of coins (whole number): ";
double total;
cin >> total;
// calculate the take home fee without rounding
double take_home_money = (total - 0.109 * total) / 100;
// Round down the take home fee to two decimal places
take_home_money = int(take_home_money * 100) / 100.0;
// What you're left with after the fee
cout << "After the fee, you take home $"
<< take_home_money << ".";
}
Also see the answer at C++ , A code to get an amount of money to convert into quarters, dimes , nickels, pennies

Related

What is Wrong With my Code?, How can i improve it any further?

The problem is that my program does not give accurate average for numbers with more than 9 digits.
Can somebody point out what am I doing wrong and how do I fix that? Is there anything I can do to improve the code any further?
The code is
#include <iostream>
using namespace std;
int main(){
cout << " Average Finder \n"; //So that the title is displayed properly.
int NUM1,NUM2,AVG; /*I am defining the variables as integers, seemed like the best option.
Should I use long float? Does that even work?*/
cout << "Type the First Number: "; // for the display
cin >> NUM1; // the program asks for the first user input and stores it in integer variable NUM1
cout << " \n";
cout << "Type the Second Number: ";
cin >> NUM2; // the program asks for the second user input and stores it in integer variable NUM2
cout << " \n";
AVG = ((NUM1+NUM2)/2); //this line calculates their average
cout << "The Average of given numbers is = ";
cout << AVG;
return 0;
}
Here is the command line executions.
PS D:\Workspace\Coding\C++> .\ALG001.EXE
Average Finder
Type the First Number: 1111111111
Type the Second Number: 1111111111
The Average of given numbers is = -1036372537
Your NUM1 and NUM2 are of type int. int variables have a maximum value, on most systems it is 2147483647.
When NUM1 = 1111111111 and NUM2 = 1111111111, then NUM1 + NUM2 will be bigger than the the maximum value 2147483647. This is called overflow.
Technically in c++ this is undefined behaviour, but on most systems it will wrap around giving you negative values and explaining your output.
If you want your variables to store larger values, use long or even long long.
You'll want to use floating point for the average. And beware of integer division:
double average = 0.0;
average = (1 + 2 + 3) / 3.0;
std::cout << average << "\n";
With integer division, 1 / 3 == 0.

C++, Interest Calculator not displaying correct output

The question asks "Write a program that reads an initial investment balance and an interest rate, then prints the number of years it takes for the investment to reach one million dollars."
The inputs I've been putting in are 100 for amount, and 3 for interest rate. But when i compile and run, the output is 29 which is incorrect as the amount is only 187 which isn't at all close to a million.
/*
Question: Write a program that reads an initial
investment balance and an interest rate, then
prints the number of years it takes for the
investment to reach one million dollars.
*/
#include <iostream>
using namespace std;
int main()
{
//Obtain user amount
double amount;
cout << "Please enter an initial investment balance ($0.00): $";
cin >> amount;
//Obtain user interest rate
double interest_rate;
cout << "Please enter an interest rate: ";
cin >> interest_rate;
//Convert interest rate to decimal
interest_rate = interest_rate / 100;
int time = 1;
//Calculate how many years
while (amount < 1000000)
{
amount = amount * (1 + (interest_rate * time));
++time;
}
//Display years
cout << "Years to reach one million: " << time;
return 0;
}
The output i am expecting is:
"Years to reach one million: 333300"
since 333300 is exactly one million.
In one year, the amount will grow to
amount * (1 + interest_rate)
and in two years, the amount grows to
amount * (1 + interest_rate) * (1 + interest_rate)
assuming annual compounding of your interest rate. Your inclusion of time, and the continuous multiplication by amount are errors.
Note that there is a closed form solution. For rate r, initial amount I, final amount A, the number of years t is
t = ln(A / I) / ln(1 + r)
which you need to round up.

writing a code for time to double annual interest rate

I'm trying to write a code for annual interest rate that lets you enter any amount, and it will show you approximately how many years it takes for your money to at least double. The given interest rate is 5% yearly. Thing is, it's not working properly and it's displaying absurdly high numbers, like 200 years or so.
#include <iostream>
using namespace std;
int main() {
int deposit;
int counter;
cout << "Deposit an amount NO LESS than 1000." << endl;
cin >> deposit;
for (deposit ;; deposit = 1.05 * deposit) {
counter = counter+1;
if (deposit >= 2 * deposit) {
cout << endl;
cout << "Your money will double in "<< counter <<" years." << endl;
break;
}
}
}
Instead of using a loop, you could calculate the time taken to double the money directly.
The amount of money is not interesting, so you don't need to store the amount of money. It's only the rate of return that's interesting.
You can calculate it directly as log(2) / log(r) where r is the rate of return. For example log(2) / log(1.05) gives you the exact time to double an initial amount of money with a 5% return.
Include the standard <cmath> header to get std::log().
#include <iostream>
#include <cmath>
int main() {
double yearsToDouble = std::log(2) / std::log(1.05);
std::cout << "Your money will double in "<< yearsToDouble << " years." << std::endl;
}
Use a variable to store the initial deposit so that it can be compared to the cumulative amount with interest.
for (float initdeposit = deposit;; deposit = 1.05 * deposit)
{
counter = counter+1;
if (deposit >= 2 * initdeposit)
{
cout << endl;
cout << "Your money will double in "<< counter <<" years." << endl;
break;
}
}
a.exe
Deposit an amount NO LESS than 1000.
1000
Your money will double in 16 years.
Note: No matter what the amount is, the time taken to double will be the same always. :)
if (deposit >= 2 * deposit) {
cout << endl;
cout << "Your money will double in "<< counter <<" years." << endl;
break;
}
In the above if statement you are expecting deposit to be greater than or equal to 2 times of deposit. Which can only be true in case if the value of deposit is zero or less than zero.
I will suggest you to use a temp variable to keep the input value of deposit and proceed.
To add to the other answers, which are largely correct in pointing out that deposit > 2*deposit can never be true (you need a second variable to record the initial value!), the only reason your loop ends at all is because deposit gets so large that 2*deposit "wraps around" due to overflow.
This appears to make 2*deposit bigger than deposit (logically impossible — you need to fix this comparison!) although strictly speaking the results are undefined.
Apparently this happens to you after 200 or so iterations.
As for suggestions to switch to a floating-point type like double, this is tempting, and may be sufficient in this simple case, but as a general rule you should avoid floating-point when you don't need it as it introduces complexities and inaccuracies for very little gain.
I would recommend counting in integer pennies, or tenths of pennies, instead. You can achieve it by multiplying the input by 100 or 1000. The resulting incremental multiplication by 1.05 will have a rounding factor, then, but this is what the banks will be doing too!
This line
if (deposit >= 2 * deposit) {
Will not evaluate to true (unless deposit is negative or barring someedge case). You probably wanted to compare it to an initial value. So after this:
cin >> deposit;
I would put
double initialDeposit = deposit;
And then change the other line to
if (deposit >= 2 * initialDeposit) {

Attempting to construct a milage calculator

I am attempting to construct a mileage calculator. The design is like this,
If a person drives 100 miles or less then the amount they shall be paid 25 cent per mile.
If a person drives in excess of 100 miles, they shall be paid the initial 25 cents for their first 100 miles in addition to 15 cents for every mile over 100 mile...
So an example would be
10 miles would earn the person a dollar, while 250 miles would earn (25 for the first 100 + 22.50 for the second 150) to a grand total of 47.50..
When I hit start without debugging, the program goes to the black screen to put values in. But then I receive an error message.. I am trying to figure out what it means.
I am using microsoft visual studio 2008. C++ coding.
#include <iostream>
using namespace std;
int main()
{
int varOne ;
cout << "Enter your favorite number" << endl;
cin << varOne << endl;
if(varOne <= 100)
cout << (1/4)*(varOne)<< endl;
if (varOne>= 100)
cout << (.15 * (varOne-100)) + (.25 * 100) <, endl;
return 0;
}
Debug Error!
Program ... isual Studio
2008\Projects\practice\Debug\rorioodweorrfhur.exe
Module: ... isual studio
2008\Projects\practice\Debug\rorioodweorfhur.exe
File:
Run-Time Check Failure #3 - The variable 'var1' is being used without being initialized.
(Press Retry to debug the application)
Here are some simple errors I noticed in your code
cin << varOne << endl;
It should be
cin >> varOne ;
Next error
cout << (.15 * (varOne-100)) + (.25 * 100) <, endl;
This should be
cout << (.15 * (varOne-100)) + (.25 * 100) << endl;
Here are some logical errors.
In your If statements, you are checking >= and <= , Check for equality only once. Change
if(varOne <= 100)
to
if(varOne < 100)
Also change
cout<< (1/4)*(varOne) << endl;
to
cout<< (varOne)/4 << endl;
This is because 1/4 will give 0

C++ possible coin combinations using while loop

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).