I made this program in C++, simple calculation of an interest rate of a bank a while back as part of a homework assignment. The answer is incorrect by a small margin but I still cannot understand why, and the mistake gets higher as I try higher input numbers...
The instructions on how to get this problem are commented as first lines of the program.
I tried switching the involved variables from float to double then to long double and its still the same answer...
Can anyone please figure out why?
// Homework 2 Task 1.cpp : Show bank balance after loan with user-input factors
//Try the code with 100 deposited sum, 5% interest and 3 months total time
//The answer will show 302.087 whereas the true answer should be 302.507
#include "stdafx.h"
#include <iostream>
using namespace std;
long double compoundVal(unsigned int, unsigned short int, unsigned short int);
void main()
{
unsigned int DepSum;
unsigned short int IntRate, NrMonths;
cout << "Please enther the amount you expect to deposit each month: ";
cin >> DepSum;
cout << "\nThe amount of money that you will have in your account after 6 months with Inte-rest Rate of 5% will be: "<<compoundVal(DepSum, 5, 6); //Answering the first part of this task, where the user has to specify the Deposit Sum, and will receive the amount after 6 months with interest of 5%
cout << "\n\nYou can also see the account balance with interest rate and number of months of your choice.\nPlease enter the Interest Rate of your choice: ";
cin >> IntRate;
cout << "\nNow enter the number of months you intend to have the account: ";
cin >> NrMonths;
cout << "\nThis will be your account balance: " << compoundVal(DepSum, IntRate, NrMonths) << endl;
}
long double compoundVal(unsigned int d, unsigned short int i, unsigned short int n){
long double c = (1.0 + (i / 1200.0)); //Finding the monthly percentage, and because the user inputs the yearly interest in %, we need to remove the %(*0.01) and /12 for 12 months/year.
return((1.0 + (n - 1)*c)*d*c); //The math formula that will give us the results of the calculation.
}
The formula you are using appears to be wrong - but I'm not sure where you got it or what it actually represents. The expected answer is for simple periodic compounding interest. In other words, each month you calculate newbalance = balance * (1 + annualrate/12) + deposit). Iterating that 3 times for your required three months gives the expected answer of $302.5069, instead of the lower value $302.0868 you get from your formula.
The formula you are using is wrong.
The value of the first month's deposit at the end of 3 months: d.c^3
The value of the second month's deposit at the end of 3 months: d.c^2
The value of the third month's deposit at the end of 3 months: d.c
If you generalize it to N months, the total value of your deposit at the end of N months will be:
d(c + c^2 + c^3 + ... + c^N)
The value of that sum is: d.c.(c^N - 1)/(c-1)
If you plugin this formula you'll get the correct answer: 302.507.
The formula
sum = d(c + c^2 + c^3 + ... + c^N)
Multiplying both side by c,
sum.c = d(c^2 + c^3 + c^4 + ... + c^(N+1))
Subtracting the two equations,
sum(c-1) = d(c^(N+1) - c) = d.c(c^N - 1)
sum = d.c(c^N - 1)/(c-1)
Related
I have this assignment in which i will show the prompt for it:
Write a program that reads in a set of test score data from the user. (Test
scores should be entered in decimal form to represent the percentage grade). Once the user has
finished entering the test scores (entering -1 will signal the end of input), print out the number of
tests entered, the average of the tests, and the standard deviation. Use the following formula
(Welford’s method) to calculate the standard deviation:
(Standard Deviaton Formula)
You can compute this quantity by keeping track of the count (number of tests), the sum, and the sum
of squares as you process the input values.
Note: Although there are other ways to calculate the standard deviation, please use this method. This
method is used since it only requires one pass of the data. Do not use arrays or vectors.
Now the code below is what I have so far. In the terminal, I'm getting wrong numbers for the average and Std. Deviation outputs (Terminal Output). Is there anything wrong with my math? Any help is appreciated. EDIT: Here is the data I'm using and the expected results I should be getting:
1. 67.8
2. 95.6
3. 89.5
4. 76.7
5. 71.3
6. 83.2
7. 90.6
8. 56.1
9. 98.6
10. 85.2
result:
Number of Test Scores: 10
Average : 81.46
Std. Deviation: 13.39
Code
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double sum = 0;
double sumSq = 0;
double grade = 0;
int numtests = 0;
cout << "Enter the test scores. Once finished, enter -1 to end input.\n";
cin >> grade;
while (grade != -1)
{
cin >> grade;
sum = sum + grade;
sumSq = sumSq + pow(grade, 2);
numtests++;
}
double average = (sum / numtests);
double std = (sumSq - numtests * pow(average, 2) / (numtests - 1));
cout << "The number of scores: " << numtests << "\n";
cout << "Average: " << average << "\n";
cout << "Std. Deviation: " << std << "\n";
return 0;
}
You've written the function so "-1" is part of the calculation which isn't what you want. I could fix it for you, but I think you can take it from that hint. And now that I look again, the first number is NOT part of your calculation.
just finished my first week of C++(using Visual Studio 2017), I wrote a program that asks the user for the amount of money and will print the number of bills and coins. it works at the beginning, but sometimes it just prints wrong number.(when the user input $1.28, it shows 1 dollar, 1 quarter and 2 pennies.)
here is my code, is there anything wrong? the algorithm or the data type?
#include<iostream>
using namespace std;
float Q = 0.25;
float D = 0.10;
float N = 0.05;
float P = 0.01;
float Dollar = 1;
float money;
float dollars, quarters, dimes, nickels, pennies;
int main() //to break money into coins.
{
cout << "how many money do u have?" << endl;
cin >> money;
dollars = (int)money;
quarters = (int)((money - dollars*Dollar)/Q);
dimes = (int)((money - dollars*Dollar - quarters*Q) / D);
nickels = (int)((money - dollars*Dollar - quarters*Q - dimes*D) / N);
pennies = (int)((money - dollars*Dollar - quarters*Q - dimes*D - nickels*N) / P);
cout << "$" << money << " can be break into :" << endl;
cout << dollars << " dollars. " << endl;
cout << quarters << " quarters. " << endl;
cout << dimes << " dimes. " << endl;
cout << nickels << " nickels. " << endl;
cout << pennies << " pennies. " << endl;
}
how to avoid the loss of precision when trying to round number? (C++)
When you convert from floating point to integer, the fractional part is truncated. To ensure no loss of integer precision (getting the right "whole"), add 0.5 to the result each time e.g:
quarters = static_cast<int>(((money - dollars*Dollar)/Q)+0.5);
This however doesn't work when the result is negative e.g:
50.5 - 100 = -49.5 -> +1 = -48.5 -> -48... not 49
For negatives you would want to therefore subtract 0.5.
I'd assume, that in the line
pennies = (int)((money - dollars*Dollar - quarters*Q - dimes*D - nickels*N) / P);
the part (money - dollars*Dollar - quarters*Q - dimes*D - nickels*N) will produce a value, that is not exactly .03, but a tad below. This is due to the nature of floating point arithmetic, you should read on that. Given that it's something like .029999999995, division by .01 will not yield 3.0, but maybe 2.9999999995. Since you are not rounding, but casting the value to an integer, the whole part after the period will be thrown away, hence it results in 2 pennies.
How can you solve this issue?
The simplest thing will be to round the value instead of casting it, this should yield the correct value, but this is kind of a hacky solution to an issue there is an exact solution for. You could also try to use double instead of a float, but this, too, would not solve the issue. You might get this correct, but the same a similar bug could still occur.
Store whole pennies
You could store the whole amount as an integer (whole pennies)
int amountInPennies;
int penniesPerDollar = 100;
int penniesPerQuarter = 25;
int penniesPerDime = 10;
int penniesPerNickle = 5;
int totalDollars = amountPennies / penniesPerDollar;
int totalQuarters = (amountPennies - totalDollars * penniesPerDollar) / penniesPerQuarter;
...
Decimal types
In a real world application dealing with money (well, depending on the type) you'd most likely go with some kind of decimal type instead of a float. According to this answer there are libraries with arbitrary precisions arithmetic available under the GNU license. You could still roll your own decimal type, that - more or less - does what I presented in the first approach. This might be a great excercise to learn, but maybe a ready-made library would be the better option when it comes to a real world application.
Very new to C++. Doing my best to get a good handle on this.
The extra couts after the read statements were for troubleshooting purposes to make sure it was actually reading user input.
I feel like this is a dumb question but iv been scouring the forums to find something similar to my issue.
I cannot for the life of me figure out how to get this program to start calculating the correct interest. When comparing to an online interest calculator it comes up with a very different number than what the program is calculating.
I have spent tons of hours troubleshooting this and texting different algorithms but I have yet to come out on-top. I dont normally like asking for help because I learn by struggling through something but this one is throwing me for a loop...
So I think I might either be having an issue with the libraries I am using or a calculation error. I know the code is a bit messy and I am learning how to clean it up but as for now I just want to get the code calculating compound interest based off of user input. I have added comments to explain what each section of code does to help with my messiness.
I dont believe its a syntax error but with the way I am either using a few of the commas in the algorithm or my parentheses are somehow wrong.
the formula I am using is,
A = P (1 + r/n)^(nt)
Amount = principle (1 + interest rate/times compounded)^(rate, times
compounded)
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double rate;
double time;
double principle;
double amount;
double amount2;
//Asking for the amount of money that the user would like to invest
cout << "What is the amount of money you would like to invest? ";
cin >> principle;
cout << principle << endl;
//Asking for the interest rate that will be compounded annually
cout << "What is the interest rate you would like to calculate? ";
cin >> rate;
//interest rate divided by 100 so it can be multiplied by the principle and the amount of time the money will be invested later in code.
rate /= 100;
cout << rate << endl;
//Asking for the amount of years that the user will invest.
cout << "How many times would you like to compound your money? ";
cin >> time;
cout << time << endl;
//calculation for amount of money that will be made after all user input is input
amount2 = pow(rate, time);
cout << amount2 << endl;
amount = (principle * (1 + rate/time), amount2);
//Output data after all user data is input and calculated.
cout << "Your will have "; cout << amount; cout << " dollars in
interest! "<< endl;
return 0;
}
This line:
amount = (principle * (1 + rate/time), amount2);
Does absolutely nothing with principle * (1 + rate/time). That expression is evaluated, and then the results are discarded, leaving amount to be assigned the value in amount2. I assume you were trying to call a function with those two expressions as parameters.
http://en.cppreference.com/w/cpp/language/operator_other#Built-in_comma_operator
In a comma expression E1, E2, the expression E1 is evaluated, its
result is discarded, and its side effects are completed before
evaluation of the expression E2 begins.
Now that we have your formula:
A = P (1 + r/n)^(nt)
Amount = principle (1 + interest rate/times compounded)^(rate * times compounded)
I am not certain you are computing the formula you have listed above, and note the correction to the second line, where I replace the comma with multiplication.
amount2 = pow(rate, time);
Computes rate^time, where you should have:
amount2 = 1 * time; // Where one is the times compounded per period (year)
So that your other line can read:
amount = principle * pow((1 + rate, amount2);
Because you are compounding once per year, you are dividing rate by 1, not by the number of years. By the same token, amount2 is now strictly equal to time;
I'm taking a C++ class, as I just started my first year of college and it has been destroying me. I have been attempting for hours to do my homework but can't come to a solution.
My assignment is to make a C++ program that when given minutes will tell you years and days.
We have been using float and cout and cin in class and some % and / structures which are foreign to me. If someone could help that would be great because I lost all hope at this point.
#include <iostream>
using namespace std;
float = minutes
float = hours
float = days
float = years
float = seconds
int main()
{
using namespace std;
int days, years, minutes, hours, seconds;
cout << "Please Enter Minutes" << endl;
cin >> minutes;
days = input_minutes / 60 / 60 / 24;
hours = (input_minutes / 60 / 60) % 24;
minutes = (input_minutes / 60) % 60;
seconds = input_minutes % 60;
cout << days << " seconds = " << years << " years ";
cin.get();
cin.get();
return 0;
}
I took the liberty to look at the code that you have into the comment box;
first thing :
Declare a variable to store the input value or save the result of a computation
int days; //<--- declaration of a int variable called days
so this in line I don't know what you were trying to do but float = minutes float = hours float = days float = years float = seconds
Please don't do it
second thing:
Don't repeated `using namespace std` twice. Therefore remove it from the `int main` function.
Third :
your computation is kinda OFF, try to solve mathematically then code it.
your code should look like that: (This is not the answer)
#include <iostream>
using namespace std;
int main()
{
int days, years, input_minutes, hours, seconds,minutes;
cout << "Please Enter Minutes" << endl;
cin >> input_minutes;
days = input_minutes / 60 / 60 / 24;
hours = (input_minutes / 60 / 60) % 24;
minutes = (input_minutes / 60) % 60;
seconds = input_minutes % 60;
cout << days << " seconds = " << years << " years ";
system("Pause");
return 0;
}
I can give you a little help on what each of those means. Here are the non-super technical definitions.
A float is an integer that can have decimal places.
cout Will output the value next to <<
cin will store a value from an input (cin >> x) will store the user input in x.
% is the modulus character. It will return the remainder after the division of two numbers. 3%2 will return 1.
/ is just simple, plain old, division.
Joe, I think we shouldn't do that job for you, and this is not exactly a "technical" question. Considering this, I will try to give you some ideas.to get some extra scores:
1 - take the user input, "the number of minutes" from command line args, like:
int main(int argc, char *argv[]) {
int num_mim = atoi(argv[1]);
2 - to take the number of years do int num_years = num_mins / (60 * 24 * 365);
(not taking into account leap years)
3 - to take the number of days do int num_days = num_mins % (60 * 24 * 365) / 60 / 24;
of course simplify the operations by performing the multiplications and divisions that can be made by hand if you want.
% is the modulos operator, it gives you the remainder of the dvision, here we use it to get the remainder of minutes from the years cound and express it in days.
Now it is up to you, look for additional sources of info and assemble your homework.
I'm Having problems with to of the questions on my C++ homework.
Write a program to analyze gasoline price in the past 10 days. First, ask the user to enter the prices. Then do the following:
(a) Calculate and display the average price in the first 5 days and the average price in the second 5 days
(b) Compare the two average prices. Determine and report which one is higher (or they are the same).
(c) Compare each day’s price (except day 1) with the price the day before. Determine whether it became higher, lower or remained the same. Count and report the number of days the price was higher than, lower than and the same as the price the day before, respectively.
i'm not sure how to compare how to compare the first five days with the last five days, and part c I'm completely lost on....
i'm not looking for someone to do my homework for me, but a push in the right direction would be a great help!
here is what I have made so far:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
double gasPrice[10];
double firstFive = 0.0;
double lastFive = 0.0;
double ffAvg = 0.0;
double lfAvg = 0.0;
for (int x = 0; x < 10; x = x + 1)
{
gasPrice[x] = 0.0;
}
cout << "You will be asked to enter daily gas prices for 10 days."<< endl;
ofstream gasprice;
gasprice.open("gasprice.txt", ios::app);
if (gasprice.is_open())
{
for (int x = 0; x < 10; x = x + 1)
{
cout << "Enter the gas price " << x+1 << ": ";
getline(cin, gasPrice[x];
}
if ( ffAvg > lfAvg)
{
cout << "The first five days have a lower gas price " << ffAvg << lfAvg << endl;
}
else if ( ffAvg < lfAvg)
{
cout << "The last five days have a lower gas price " << ffAvg << lfAvg << endl;
}
system("pause ");
return 0;
}
Read the requirements like they are a description rather than a computer formula. It can become overwhelming when learning something for the first time and we get drowned by the things that would come natural in another environment.
Anyway, you are not to compare the days individually but an AVERAGE of the days. So you first need to compute the AVERAGE of the first five and the AVERAGE of the second five days, then compare that.
For the second part of your question, aggregators for your totals is the push I would give you.
Hope this helps.
Break down the problem in to a series of stages: Firstly, you need to get 10 input prices from the user, and store them in an array of size 10.
Next, you need to compute the average price for the first five days (i.e. for values in index 0-4 of your array), and store it in ffAvg, you can do this using the following simple for loop:
double sum;
for( int i = 0; i < 5; i++ )
{
sum += gasPrice[i];
}
double ffAvg = sum / 5;
You then do this with the 2nd 5 days, storing the average in lfAvg.
The next part of your task is to compare the averages, you can doing this using if and else if statements, for example, if you wanted to compare to numbers, num1 and num2 you might do the following:
if( num1 > num2 )
{ /* Do something */ }
This will compare num1 and num2 and if num1 is greater than num2 it will perform the code in the braces.
To do the last comparison you simply combine what we have done above on a per day basis. Try to experiment with various ways of doing it, as this will help you to learn more.
Hope this helps you! :)
EDIT: I also noticed that you've not closed a lot of your bracers, you must always do this so the compiler can work properly. Every { must have a corresponding }, else the compiler should throw up errors, and not compile.
I sugest doing as following:
double average1=0.0;
for(int i=0;i<5;++i) {
average1 += values[i];
}
average1/=5.0;
double average2=0.0;
for(int i=5;i<10;++i) {
average2 += values[i];
}
average2/=5.0;
Also, take a look at std::vector, it may help you in further exercises:
http://www.cplusplus.com/reference/stl/vector/
You should first compute the average of the first and last 5 days. The average is defined by the sum divided by the number of items. So your average will be (gasPrice[0] + gasPrice[1] + gasPrice[2] + gasPrice[3] + gasPrice[4]) / 5.0.
You should probably make this computation in a loop similar to the one you have for getting the input. The loop should only iterate 5 times.