writing a code for time to double annual interest rate - c++

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

Related

How to initialize local variable to unkown value C++

trying to make my first post right so here goes.
I ran into this question and have not been able to figure it out. I keep receiving the error:
error C4700: uninitialized local variable 'miles' used
I have scavenged over all of StackOverflow and keep running into the same answer: I have to initialize my local variable, but when I do that I am creating a set value. I want to set my local variable 'miles' to an unknown value because I want the user to be able to set the value when the program runs.
Everything ran great until I tried to cast the end value 'miles'so that it would truncate.
Please correct me if I'm using incorrect terminology. Fresh-out-of-the-womb-to-programming. And thank you to everyone in advance.
Question:
Write a program that prompts the capacity, in gallons, of an automobile fuel tank and the miles per gallon the automobile can be driven. The program outputs the number of miles the automobile can be driven without refueling. Numbers entered for capacity must allow entry of capacity being an integer and the miles per gallon in decimals. The number of miles must be output to the next lowest integer (without decimals).
#include "stdafx.h"
//include statement
#include<iostream>
//include namespace statement
using namespace std;
//main function
int main()
{
//variable declaration
double capacity_Gallons;
double miles_Gallon;
double miles = static_cast<int>(miles < 0 ? miles - 0.5 : miles + 0.5);
//inputting capacity of automobile
cout << "Enter the capacity of the automobile fuel in gallons: ";
cin >> capacity_Gallons;
cout << endl;
//inputting the miles per Gallons
cout << "Enter the miles per gallons the automobile can be driven: ";
cin >> miles_Gallon;
cout << endl;
//calculating miles
miles = capacity_Gallons * miles_Gallon;
//display output data
cout << "Number of miles driven wihtout refueling: " << miles << endl;
//pause system for some time for user continuation
system("pause");
} //end main
You should take out that line entirely, and change the later line to double miles = capacity_Gallons * miles_Gallon;.
Instead of your handcrafted rounding code it would be better to use the standard rounding function in the display statement, ... << std::lround(miles) << ... although your assignment stipulation says you should round down , not round to nearest as you are currently doing. (So you can just cast to int there).
You don't need to declare miles there, you can declare it at the point it has a value.
#include<iostream>
int main()
{
//inputting capacity of automobile
double capacity_Gallons;
std::cout << "Enter the capacity of the automobile fuel in gallons: ";
std::cin >> capacity_Gallons;
std::cout << endl;
//inputting the miles per Gallons
double miles_Gallon;
std::cout << "Enter the miles per gallons the automobile can be driven: ";
std::cin >> miles_Gallon;
std::cout << endl;
//calculating miles
double miles = capacity_Gallons * miles_Gallon;
//display output data
std::cout << "Number of miles driven wihtout refueling: " << miles << std::endl;
//pause system for some time for user continuation
system("pause");
}
As an aside, using namespace std is a bad habit.

Coin machine regarding decimals

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

gauge the rate of inflation for c++

Write a program to gauge the rate of inflation for the past year. The program asks for the price of an item (such as a hot dog or a 1-carat diamond) both one year ago and today. It estimates the inflation rate as the difference in price divided by the year-ago price. Your program should allow the user to repeat this calculation as often as the user wishes. Define a function to compute the rate of inflation. The inflation rate should be a value of type double giving the rate as a percent, for example 5.3 for 5.3 percent.
Your program must use a function to compute the rate of inflation. A program which does not use a function will be awarded a score of zero, even if all tests pass.
I want to repeat the loop, but no wonder I input Y or N, the loop will also repeat. Suppose the loop should repeat when I input 'Y' or 'y'. Can anyone tell me what's wrong with my code?
#include <iostream>
#include <cmath>
using namespace std;
double calculate_inflation(double, double);
int main()
{
double yearAgo_price;
double currentYear_price;
double inflation_Rate;
char again;
do{
cout << "Enter the item price one year ago (or zero to quit) : " << endl;
cin >> yearAgo_price;
cout << "Enter the item price today: " << endl;
cin >> currentYear_price;
cout.setf(ios::fixed)
cout.setf(iOS::showpoint);
cout.precision(2);
inflation_rate=calculate_inflation(yearAgo_price, currentYear_price);
cout << "The inflation rate is " << (inflation_rate*100) << " percent." << endl;
cout << "Do you want to continue (Y/N)?" << endl;
cin >> again;
}while((again =='Y') || (again =='y'));
return 0;
}
double calculate_inflation (double yearAgo_price, double currentYear_price)
{
return ((currentYear_price-yearAgo_price)/ yearAgo_price);
}
while((again='Y') || (again='y'));
should be
while((again=='Y') || (again=='y'));
You have mistaken assignment for comparison operator. Those are different in C and C++.
The effect of your code is that Y or y is assigned to again and the new value is returned. That char is non-zero so converts to true. Thus, true is returned, and the loop turns endless.
Edit:
How you could've found it out yourself with a debugger:
The loop appears to be endless thus we need to check its condition variable. So, place a watch on the again variable and see it change when the loop condition is being evaluated. Problem found.
while ((again='Y') || (again='y') does not do what you think it does. You are assigning to the again variable.
What you want to do is use the == operator to compare again to either 'Y' or 'y'.

uninitialized?, tuitionCost, local Variable, [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
int main()
{
double tuitionCalc(int sumCreditHoursTaken);
int numCourses;
double total = 0.0;
double tuitionCost= 0.0;
cout << "\t\t This Program calculates a student's total number of\n";
cout << "\t\tcredit hours and tution for a given semester.\n";
cout << "\nPlease enter the number of Courses you will be taking this semester: ";
cin >> numCourses;
for ( int count = 1; count <= numCourses; count++)
{
double sumCreditHoursTaken;
cout << " please enter the number of credit hours for course" << count << ": ";
cin >> sumCreditHoursTaken;
total += sumCreditHoursTaken;
}
cout << fixed << showpoint << setprecision(2);
cout << "Your Total number of credit hours is: " << total << endl;
cout << "Your total tuition will be: $" << tuitionCalc(tuitionCost) << "\n\n";
return 0;
}
and the function im calling is
double tuitionCalc(int sumCreditHoursTaken)
{
double tuitionCost = 0.0;
double costCreditHour = 147.00;
double maxHoursFullTuition = 12;
double maintFeeAddOn = 29.33;`
if (sumCreditHoursTaken <= maxHoursFullTuition)
cout<< " " << (sumCreditHoursTaken * costCreditHour);
else if (sumCreditHoursTaken > maxHoursFullTuition)
cout << " " << (maxHoursFullTuition * costCreditHour) + ((sumCreditHoursTaken - maxHoursFullTuition) * maintFeeAddOn);
return tuitionCost;
}
input for number of courses is 5
and credit hours is 3,3,3.5,4,2.5
i get the total credit hours but icant seem to display the tuition cost?
thank you s
You are never actually assigning a value to tuitionCost in tuitionCalc() method, so it will always be 0.0.
To elaborate: You are returning tuitionCost from tuitionCalc(). You first initialize tuitionCost = 0.0, but never proceed to assign any calculated value to it. Thus, when you return tuitionCost, it will return the value you initialized it to: 0.0.
I haven't examined your code in detail, but if you inputs contain floating point numbers then change the type for sumCreditHoursTaken from int to double.
Also, change the parameter for the invocation of tuitionCalc from tuitionCost to total.
It seems that OP has fallen afoul of misunderstanding scope and how variables are passed to functions.
In main, OP defines tuitionCost. tuitionCalc defines another tuitionCost. These are different tuitionCosts. They represent different locations in memory and can store different values.
Next, because the tuitionCalc function is defined
double tuitionCalc(int sumCreditHoursTaken)
tuitionCalc(tuitionCost) will take tuitionCost convert it to an integer, and pass a copy into tuitionCalc where it will be used with the name sumCreditHoursTaken. One could say OP has three tuitionCalcs at this point. Not what they want.
Breaking down the tuitionCalc prototype, we see that it takes sumCreditHoursTaken, an integer and based on the name the number of credit hours taken, not a total cost. tuitionCalc also returns a double and inferring the purpose of the function from it;'s name, one would expect that it calculates and returns the tuition.
Like Anatoly states in his answer, the input to tuitionCalc should almost certainly be total, the total number of credit hours computed, and the output should be tuitionCost.
Since this has the smell of a homework assignment, it's not in the OP's best interests to fully answer the question. Instead here are a few recommendations:
Eliminate tuitionCost from main. It only serves to increase confusion. You can reuse variable names, but only do it where there is a clear benefit. If you have a cost and a function that takes and uses cost, then using cost for both makes sense. Just remember that cost inside the function is a different entity unless you pass by reference. In
void function(int & cost)
called with
function(cost);
both costs are the same. But in
void function(int cost)
called with
function(cost);
both function's cost is a copy of the caller's cost and any changes made by function will only effect the copy.
Declare variables close to where you use them. This way people reading your code don't have to scroll up and down and otherwise go hunting. It also helps you because it makes mistakes like, "Why am a calling a function that takes an int with a double?" more obvious.
Do not cout in tuitionCalc. Compute and return tuitionCost. Allow main to output tuitionCost. A function with a name like calc should only calculate. Names should describe function as closely as possible.
First of all you should create the function prototype before declaring it.
And there were some confusions in the code you have used I tried my best to omit error hope this is helpful!
#include <iostream>
#include <iomanip>
using namespace std;
double tuitionCal(double sumCreditHoursTaken);
int main() {
double tuitionCalc(int sumCreditHoursTaken);
int numCourses;
double total = 0.0;
//double tuitionCost= 0.0;
cout << "\t\t This Program calculates a student's total number of\n";
cout << "\t\tcredit hours and tution for a given semester.\n";
cout << "\nPlease enter the number of Courses you will be taking this semester: ";
cin >> numCourses;
double sumCreditHoursTaken; // you should create this variable outside the for loop
for ( int count = 1; count <= numCourses; count++)
{
cout << " please enter the number of credit hours for course" << count << ": ";
cin >> sumCreditHoursTaken;
total += sumCreditHoursTaken;
}
double tuitionCost=tuitionCal(total);
cout << fixed << showpoint << setprecision(2);
cout << "Your Total number of credit hours is: " << total << endl;
cout << "Your total tuition will be: $" <<tuitionCost<< "\n\n";// I assume this is what you want
return 0;
}
double tuitionCal(double sumCreditHoursTaken)//the parameter type is double now
{
double tuitionCost = 0.0;
double costCreditHour = 147.00;
double maxHoursFullTuition = 12;
double maintFeeAddOn = 29.33;
if (sumCreditHoursTaken <= maxHoursFullTuition)
tuitionCost=(sumCreditHoursTaken * costCreditHour);
else if (sumCreditHoursTaken > maxHoursFullTuition)
tuitionCost=(maxHoursFullTuition * costCreditHour) + ((sumCreditHoursTaken - maxHoursFullTuition) * maintFeeAddOn);
return tuitionCost;
//I don't see a point of returning the value and couting both you can
//do only one of the oprations
}

C++ passing variables in classes and getting logical errors

Here is the prompt I haven't gotten to all of it yet though:
Implement a class named GasPump that will be used to model a pump at a gas station.
A GasPump object should be able to perform the following tasks:
- Display the amount of gas dispensed
- Display the total amount charged for the amount of gas dispensed
- Set the cost per gallon on gas
- Display the cost per gallon of gas
- Reset the amount of gas dispensed and amount charged before each new usage
- Keep track of the amount of gas dispensed and the total charge
When implementing the GasPump class , you should assume that the gas pump dispenses
.10 gallons of gas per second. Write a test program in main() that prompts the user
to enter the cost per gallon of gas and how many seconds they want to pump gas for.
Then, display the number of gallons of gas pumped, the cost per gallon of gas, and
the total cost of the gas.
I am having problems calculating the amount paid and keep getting logical errors. As this code stands it will compile but it gives garbage for a calculation for amount charged.
#include <iostream>
#include <iomanip>
using namespace std;
class GasPump{
public:
void setCostPerGallon(double cpg){
costPerGallon = cpg;
}
double getCostPerGallon(){
return costPerGallon;
}
void setAmountDispensed(int seconds){
const double dispense = 0.10;
sec = seconds;
amountDispensed = dispense * sec;
}
int getAmountDispensed(){
return amountDispensed;
}
//here is the function I am having problems with, at least I think.
void setAmountCharged(double costPerGallon, double amountDispensed){
amountCharged = costPerGallon * amountDispensed;
}
double getAmountCharged(){
return amountCharged;
}
private:
double costPerGallon;
int sec;
double amountCharged, amountDispensed;
};
int main() {
double cpg = 0.0;
int seconds = 0;
GasPump pump;
cout << "Enter the cost per gallon of gas:";
cin >> cpg;
while(cpg <= 0.0) {
cout << "Enter a value greater than 0:";
cin >> cpg;
}
pump.setCostPerGallon(cpg);
cout << "Enter the amount of seconds you want to pump gas for:";
cin >> seconds;
while(seconds <= 0.0) {
cout << "Enter a value greater than 0:";
cin >> seconds;
}
pump.setAmountDispensed(seconds);
cout << "The gas pump dispensed " << pump.getAmountDispensed() << " gallons of gas." << endl
<< "At $" << pump.getCostPerGallon() << " per gallon, your total is $"
<< fixed << setprecision(2) << pump.getAmountCharged() << "." << endl;
return 0;
You never call pump.setAmountCharged(...), so the member variable amountCharged is whatever the compiler decided to initialize it to when you instantiated pump (typically 0);
To fix this, either get rid of the member variable amountCharged and do the calculation for the amount when getAmountCharged is called, or call setAmountCharged appropriately before calling getAmountCharged.
Here's the first solution:
class GasPump {
...
double getAmountCharged() {
return costPerGallon * amountDispensed;
}
...
};