Why this formula could not be calculated in c++? [duplicate] - c++

This question already has an answer here:
Dividing two integers to produce a float result [duplicate]
(1 answer)
Closed 1 year ago.
Here i want to calculate the number of sweets that i have been sold in Day 2.
int main()
{
float rate;
int left, total, sell ;
cout << "rate" ; // the rate that sweets have been sold per day
cin >> rate;
cout << "sell"; // number of sweets that have been sold in day1.
cin >> sell;
cout << "total"; // total number that the shops originally have
cin >> total;
left = total - sell;
sell = sell*(1+rate*(left/total));
cout << sell;
return 0;
}
And i want to calculate the numbers of sweets that have been sold in day2.
Assume the input are rate = 0.5, sell=100, total = 10000.
The output should be 14950. [ 10000 * (1+0.5*((10000-100)/10000)) ]
But why I still get 10000 after running the program.
Updated:
However, I have one more question. If i want to output a rounded up sell value. How could I do it? because i am not allowed to change the datatype of the variables, which means it should be still int sell; at the initialization part. I have tried cout << round((double) sell); But it still does not work.

As mentioned in the comment, you are doing an integer division. Here is the corrected code:-
#include<iostream>
using namespace std;
int main()
{
float rate;
int left, total, sell ;
cout << "rate" ; // the rate that sweets have been sold per day
cin >> rate;
cout << "sell"; // number of sweets that have been sold in day1.
cin >> sell;
cout << "total"; // total number that the shops originally have
cin >> total;
left = total - sell;
sell = sell*(1+rate*(left/(float)total));
cout << sell;
return 0;
}
I have typecasted the denominator.

Related

What's wrong with this simple piece of code? [duplicate]

This question already has answers here:
Why not use Double or Float to represent currency?
(16 answers)
Closed 3 years ago.
The code seems to work fine when it performs the first step of multiplying the number of quarters entered by 0.25, but then it just doesn't work with the next two steps.
#include <iostream>
using namespace std;
int main()
{
int quarter, dime, nickle;
int result;
quarter = 25;
dime = 10;
nickle = 5;
int numQuarters, numDimes, numNickles;
cout << "Please enter the number of quarters and press Enter: ";
cin >> numQuarters;
cout << "Please enter the number of dimes and press Enter: ";
cin >> numDimes;
cout << "Please enter the number of nickles and press Enter: ";
cin >> numNickles;
result = (numQuarters * quarter) + (numNickles * nickle) + (numDimes * dime);
cout << "The total amount of pennies is: " << result;
return 0;
}
I expect the output of 4 quarters, 10 dimes & 20 nickels to be 300 pennies
The output is 102
Edit: Code Fixed and working now!
Hmm... your code seems fine, but I think something was wrong with the Order of Operations in your Math. I just changed the value of nickel to 0.05 and the value of dime to 0.10 (I think that was a mistake in your code). I aslo moved the *100 down to the cout statement, and that helped clear things up...
#include <iostream>
using namespace std;
int main()
{
float quarter, dime, nickle, penny;
float result;
quarter = 0.25;
dime = 0.10;
nickle = 0.05;
float numQuarters, numDimes, numNickles;
cout << "Please enter the number of quarters and press Enter: ";
cin >> numQuarters;
cout << "Please enter the number of nickles and press Enter: ";
cin >> numNickles;
cout << "Please enter the number of dimes and press Enter: ";
cin >> numDimes;
result = (numQuarters * quarter) + (numNickles * nickle)+ (numDimes * dime);
cout << "The total amount of pennies is: " << result * 100;
return 0;
}
Oh, and just like what #Pete Becker said, do your calculations in pennies (whole numbers). Not only does it fix some minor errors with floats as money, it also makes your code easier to read and manipulate.

How could I properly set up this loan equation based on my code?

The question wants me to create 2 scenarios
The user accepts the dealer’s rebate offer and finances the car through his or her local credit union.
and
The user declines the dealer’s rebate offer but accepts the dealer’s lower financing rate.
It expects for me to use the periodic payment formula, which is: principal * rate / (1 – (rate + 1)-term) and use it to get either a monthly or annual payment.
The problem that I am having with my code I believe has something to do with my equations I am using to get annual or monthly loan payments, it for sure is not giving me the correct answer to my inputs and I do not know why.
I have tried changing the equations around several times and still no avail.
int main()
// these are the variables I will be using in maths for this project
double annualpayment; // what will be displayed once all is calculated annually
double monthlypayment; // what will be displayed once all is calculated monthly
double prinicple; // amount borrowed
double rate; // interest rate
double mterm; // what the user will enter for monthly term
double yterm; // what user will enter for yearly term
double years; // term of loan (yearly)
double month; // term of loan (monthly)
double sqrdMonth; // sqrt of term of loan (monthly)
double sqrdYear; // sqrt of term of loan (yearly)
char choice;
}
{
cout << "Enter your principle: " << endl; // total amount borrowing
cin >> prinicple;
cout << "Enter your your interest rate: " << endl; // interest rate on loan
cin >> rate;
cout << "Will this be (M)onthly or (Y)early payment? (enter y or m)"; // declaring if it will be a monthly or yearly payment
cin >> choice;
if (choice = 'M') // if its monthly
mterm = 12; // there are 12 months within a year
cout << "How many years will this loan be for?" << endl;
cin >> years; // I need this information for getting the exact
month = mterm * years;
sqrdMonth = sqrt(month); // I need to square root the months for the periodic payment formula
monthlypayment = (prinicple * rate) / (rate); sqrdMonth; // this is where my problem is
// ^^^^ why is it asking me to close my equation with a ';'
cout << "Your monthly loan payment is: ";
cout << monthlypayment;
if (choice = 'Y')
yterm = 1;
cout << "How many years will this loan be for?" << endl;
cin >> years;
years = yterm * years;
sqrdYear = sqrt(years); // I need to square root the years for the periodic payment formula
annualpayment = (prinicple * rate) / (rate); sqrdYear; // this is where my problem is
// ^^^^ why is it asking me to close my equation with a ';'
cout << "Your annual loan payment is: ";
cout << annualpayment;
}
}
I expect for the user to input the principle, rate, and length of loan then the compiler to do the math and then output the correct numbers. My actual results are negative numbers or irrational numbers.
Several mistakes
if (choice = 'M') // if its monthly
mterm = 12; // there are 12 months within a year
First point is that should say
if (choice == 'M') // if its monthly
mterm = 12; // there are 12 months within a year
In C++ we use == to test for equality and = to assign to a variable.
Even more seriously think about this
if (choice == 'M') // if its monthly
mterm = 12; // there are 12 months within a year
cout << "How many years will this loan be for?" << endl;
cin >> years; // I need this information for getting the exact
month = mterm * years;
Now suppose choice is not 'M' what do you think the value of mterm will be?
The answer is that it is undefined. Yet you are using the variable in the formula two lines down. It's bad to use variables with undefined values.
It looks to me that you need to restructure your code to include more statements inside of the if statement
if (choice == 'M')
{
mterm = 12; // there are 12 months within a year
cout << "How many years will this loan be for?" << endl;
cin >> years; // I need this information for getting the exact
month = mterm * years;
sqrdMonth = sqrt(month); // I need to square root the months for the periodic payment formula
monthlypayment = (prinicple * rate) / (rate); sqrdMonth; // this is where my problem is
// ^^^^ why is it asking me to close my equation with a ';'
cout << "Your monthly loan payment is: ";
cout << monthlypayment;
}
Finally this
monthlypayment = (prinicple * rate) / (rate); sqrdMonth;
I've no idea why you've got two semi-colons. Makes no sense to me, but I not sure what the formula should be. There's no mention of square roots in the formula in your question, so I'm not sure why you included one here.

C++ program on how much a person would earn over time if salary is one penny per day (Not an IT student)

I have a project to write a program that calculates how much a person would earn over a period of time if his or her salary is one penny the first day, two pennies the second day, and continues to double each day. The program should ask the user for the number of days. Display a table showing how much the salary was for each day, and then show the total pay at the end of the period. The output should be displayed in a dollar amount, not the number of pennies.
Input Validation: Do not accept a number less than 1 for the number of days worked.
This is my code so far and I can't seem to get it to work properly (not an
IT student)
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<math.h>
#include<iomanip.h>
int main()
{
int days;
double pennies = 0.01;
double total = 0.0;
double fixed;
double showpoint;
cout << "For how many days will the pay double?";
cin >> days;
cout << endl << "Day Total Pay\n";
cout << "------------------------\n";
for (int count = 1; count <= days; count++)
{
cout << count << "\t\t$\t" << (pow(2, pennies)) << endl;
}
cout << setprecision(2) << fixed << showpoint;
cout << "--------------------------------\n";
cout << "Total $\t" << total << endl;
getch();
return 0;
}
I've tried to explain the changes I have made, but if you need to know more please ask
// Headers for standard library features don't have .h on the end (normally)
#include<iostream>
#include<conio.h>
#include<stdio.h>
#include<math.h>
#include<iomanip>
int main()
{
int days = 0;
// double pennies = 0.01; Not needed.
double total = 0.0;
// If you don't initialise variables it will cause a crash or undefined behaviour.
// double fixed;
// double showpoint;
while (days < 1) // This prevents negative or 0 day contracts.
{
// You need to use the full name to cout or that abomination of a command using namespace std
std::cout << "For how many days will the pay double?";
std::cin >> days;
}
std::cout << std::endl << "Day Total Pay\n";
std::cout << "------------------------\n";
// looping from 0 while less than days is more "normal".
for (int count = 0; count < days; count++)
{
double payForTheDay = (pow(2, count));
std::cout << count << "\t\t$\t" << payForTheDay << std::endl;
total += payForTheDay; // You need to increment the total.
}
// Not sure what this is about
// std::cout << std::setprecision(2) << fixed << showpoint;
std::cout << "--------------------------------\n";
std::cout << "Total $\t" << total << std::endl;
getch();
return 0;
}
Try to replace (pow(2, pennies)) with (pennies * pow(2, (count - 1)))...
Notes:
Shouldn't pennies actually be named dollars?
To calculate the total, just increase it by the daily salary for each day (e.g. inside the loop where you output each table row).
So look at the basic of the problem. It is basically a geometric progression.
In a geometric progression sum of n numbers is;
Sn=a1((1-r^n)/(1-r))
[a1=first element(in your case 1);r=2(in this case)]
Use the formula to get number of pennies for n days.
Now convert it into dollar value.
If you need full code comment here.
Quite late, but using bitwise shift is the best thing for 2^n in my opinion. It's fast and easy to use.
int days; // = amount of days for payment;
// Add input/output logic
if (days<1) {
// Do invalid input logic
}
// Use long long if days>31
for (int K=0; K<days; K++)
cout<<"Day "<<K<<": "<<(1<<K)<<"\n;
Here 1<<K is 2^K
Alternatively, you can use a variable to save the payment
and shift it by 1 each iteration.

Calculating a new population

In a population, the birth rate is the percentage increase of the population due to births, and the death rate is the percentage decrease of the population due to deaths. Write a program that asks for the following:
The starting size of a population (minimum 2) (Prompt Enter starting size:)
The annual birth rate (Prompt Enter annual birth rate:)
The annual death rate (Prompt Enter annual death rate:)
The number of years to display (minimum 1) (Prompt Enter years to display:)
The program should then display the starting population and the projected population at the end of each year. It should use a function that calculates and returns the projected new size of the population after a year. The formula is
N = P(1 + B)(1 - D)
where N is the new population size, P is the previous population size, B is the birth rate, and D is the death rate. Annual birth rate and death rate are the typical numbers of births and deaths in a year per 1000 people, expressed as a decimal.
So, for example, if there are normally about 32 births and 26 deaths per 1000 people in a given population, the birth rate would be .032 and the death rate would be .026.
Here is my code; I am having trouble figuring out how to do the calculation.
#include "stdafx.h" // Defines IDE required "pre-compiled" definition files
#include <iomanip>
#include <iostream>
using namespace std
int main ()
{
double startPop, // To hold the starting population.
float birthRate, // To hold the birth rate.
float deathRate; // To hold the death rate.
int numYears; // To hold the number of years to track population changes.
// Input and validate starting population
cout << "This program calculates population change.\n";
cout << "Enter the starting population size: ";
cin >> startPop;
while (startPop < 2.0)
{
cout << "Starting population must be 2 or more. Please re-enter: ";
cin >> startPop;
}
// Input and validate annual birth and death rates
cout << "Enter the annual birth rate (as % of current population): ";
cin >> birthRate;
while (birthRate < 0)
{
cout << "Birth rate percent cannot be negative. Please re-enter: ";
cin >> birthRate;
}
birthRate = birthRate / 100; // Convert from % to decimal.
cout << "Enter the annual death rate (as % of current population): ";
cin >> deathRate;
while (deathRate < 0)
{
cout << "Death rate percent cannot be negative. Please re-enter: ";
cin >> deathRate;
}
deathRate = deathRate / 100; // Convert from % to decimal.
cout << "For how many years do you wish to view population changes? ";
cin >> numYears;
while (numYears < 1)
{
cout << "Years must be one or more. Please re-enter: ";
cin >> numYears;
population = projectedNewSize(populationStartingSize, annualBirthRate, annualDeathRate);
cout << population << endl;
populationStartingSize = population;
}
printPopulations(startPop, birthRate, deathRate, numYears);
return 0;
} // End of main function
You can do this recursively or using a simple for loop.
E.g. Say if the numYears = 10, you would want to loop 10 times.
Create a temporary variable before your for loop and assign it the value of your startPop, e.g. endPop.
Then, starting with an initial population size of endPop, and death rate of deathRate as well as birth rate of birthRate, you calculate the population size after one year.
Having computed the population after one year in the first loop, you update endPop with the new value.
Subsequently, in the second loop, you use endPop once again as the new starting population size and the cycle repeats itself up till the end of your for loop, i.e. when 10 years have passed.
You did not declare the variable population in the above code snippet before using it.
Implementation:
while (numYears < 1)
{
cout << "Years must be one or more. Please re-enter: ";
cin >> numYears;
}
double population = populationStartingSize;
for ( int i = 0; i < numYears; i++) {
population = projectedNewSize(population, annualBirthRate, annualDeathRate);
cout << "After " << i+1 << "years: " << population << endl;
}
}
Take note that there is chance of over- and under-flow if your number gets too small or too big.
Implementation:
double projectedNewSize(double populationStartingSize, float annualBirthRate, float annualDeathRate) {
return populationStartingSize * (1 + annualBirthRate) * (1 - annualDeathRate);
}
For reading of numYears, you could consider using a do-while loop, :p.

How to loop certain aspects of a program

I'm trying to loop the assignment scores and totals based on whatever the user inputs in for n. I have been searching around and just hitting duds, which is what the whole deal with the int i variable is at the moment. I can't get things to loop properly and right now this doesn't even compile because of that pesky i I have in there. You take out that i and the program runs fine with the exception that nothing becomes of the n input.
/**
File: project_2_14.cpp
Description: Write a program that calculates the total grade for N classroom exercises as a percentage. The user should input the value for N followed by each of the N scores and totals. Calculate the overall percentage (sum of the total points earned divided by the total points possible.) and output it as a percentage. Sample input and output is shown below.
Created: Friday, September 11th, 2015
Author:
email:
*/
#include<iostream>
#include<vector>
using namespace std;
int main()
{
float s; // assignment score
float t; // total points worth
float p; // percentage
int n = 0;
//input the number of assignments
cout << "How many assignments are there? " << endl;
cin >> n;
for (int i=0; i < =n; i++)
{
//input the total points earned for assignment
cout << "What is the score earned for this assignment? ";
cin >> s;
//input the number of points assignment is worth
cout << "How many points was the assignment worth? ";
cin >> t;
//calculate percentage
p = (s / t)*100;
}
//output score
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
cout << "Total score: " << p << "%"<< endl;
return 0;
}
You should remove the int n = 0; and it should be simply int n.
and you should use <=, without any spaces between both characters.
EDIT:
As you can see here: http://ideone.com/SeNum8 it already loops correctly :)
#include<iostream>
#include<vector>
using namespace std;
int main()
{
float s; // assignment score
float t; // total points worth
float p; // percentage
int n;
//input the number of assignments
cout << "How many assignments are there? " << endl;
cin >> n;
for (int i=0; i <=n; i++)
{
//input the total points earned for assignment
cout << "What is the score earned for this assignment? ";
cin >> s;
//input the number of points assignment is worth
cout << "How many points was the assignment worth? ";
cin >> t;
//calculate percentage
p = (s / t)*100;
}
//output score
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
cout << "Total score: " << p << "%"<< endl;
return 0;
}