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

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.

Related

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

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.

Length conversion program cannot convert decimal number in C++

I have to write a program that takes length as input in feet and inches and the program should then convert the lengths in centimeters and display it on screen. So this is my code:
#include "pch.h"
#include <iostream>
using namespace std;
int main()
{
double totalinches;
double centimeter;
float inch_to_centimeter = 2.54f;
int feet_to_inch = 12;
int feet;
int inch;
cout << "Enter the length in feet:";
cin >> feet;
cout << "Enter the length in inches:\n ";
cin >> inch;
totalinches = (feet * feet_to_inch) + inch;
cout << "Total length in inches:\n ";
cout << totalinches;
centimeter = totalinches * (inch_to_centimeter);
cout << "The number of centimeter= ";
cout << centimeter;
When I run the code, the code can only calculate natural number (non-decimal number) but whenever I type decimal number, the code is error. This is the error that I got when I type decimal number. The code itself skip the "Enter the length in inches" and the result is always 60 and 152.4. Sorry for my bad English and i am new to code.
Enter the length in feet:5.74
Enter the length in inches:
Total length in inches:
60The number of centimeter= 152.4
C:\Dev\C++\HomeWork\Debug\HomeWork.exe (process 22468) exited with code 0.
To automatically close the console when debugging stops, enable Tools->Options->Debugging->Automatically close the console when debugging stops.
Press any key to close this window . . .

Stumped with a transient population program in c++

this is my first time posting on here. Whenever I've gotten stuck on a programming problem, I've typically been able to find enough information to get me unstuck. I'm afraid that the issue I'm having though, I can't quite find an answer to. It's something I'd need someone to look at to tell me what I may be doing wrong in my code.
I have the program running successfully, and it DOES work. The issue however, is that my produced output is off by a few numbers when compared to the expected output on My Programming Lab. I'm really not sure of what to do to produce the correct output. Allow me to post both my source code, and a screenshot MPL's results screen.
SOURCE CODE:
#include <iostream>
using namespace std;
int populationCalculator(int, double, double, int, int);
int main()
{
int startingPopulation, newArrivals, peopleWhoLeft, years,
newPopulation, finalPopulation;
double deathRate, birthRate;
cout << "This program calculates population change.\n";
cout << "Enter the starting population size: ";
cin >> startingPopulation;
while (startingPopulation < 2)
{
cout << "\nThe starting population may not be less than two. Please
re - enter: ";
cin >> startingPopulation;
}
cout << "Enter the annual birth rate (as % of current population): ";
cin >> birthRate;
while (birthRate < 0)
{
cout << "\nBirth rate percent cannot be negative. Please re -
enter:";
cin >> birthRate;
}
birthRate = birthRate / 100;
cout << "Enter the annual death rate (as % of current population): ";
cin >> deathRate;
while (deathRate < 0)
{
cout << "\nDeath rate percent cannot be negative. Please re -
enter: ";
cin >> deathRate;
}
deathRate = deathRate / 100;
cout << "How many individuals move into the area each year? ";
cin >> newArrivals;
while (newArrivals < 0)
{
cout << "\nArrivals cannot be negative. Please re - enter: ";
cin >> newArrivals;
}
cout << "How many individuals leave the area each year? ";
cin >> peopleWhoLeft;
while (peopleWhoLeft < 0)
{
cout << "\nDepartures cannot be negative. Please re - enter: ";
cin >> peopleWhoLeft;
}
cout << "For how many years do you wish to view population changes? ";
cin >> years;
while (years < 1)
{
cout << "\nYears must be one or more. Please re - enter: ";
cin >> years;
}
newPopulation = populationCalculator(startingPopulation, deathRate,
birthRate, newArrivals, peopleWhoLeft);
cout << "\nStarting population: " << startingPopulation << endl;
for (int loopCount = 1; loopCount <= years; loopCount++)
{
newPopulation = populationCalculator(newPopulation, deathRate,
birthRate, newArrivals, peopleWhoLeft);
cout << "Population at the end of year " << loopCount << " is: " <<
newPopulation << endl;
}
system("pause");
return 0;
}
int populationCalculator(int Population, double deathRate, double birthRate,
int newArrivals, int peopleWhoLeft)
{
int newPopulationCount;
newPopulationCount = Population + (Population * birthRate) - (Population
* deathRate) + newArrivals - peopleWhoLeft;
return newPopulationCount;
}
MPL RESULTS:
http://imgur.com/a/mRmpc
I really will appreciate if anyone can help me figure out why my produced output is off by a few numbers.
Step through your code. You're returning an int where you have double and int multiplication. Make sure that you aren't truncating values that might need to be rounded up or down.
Does birth happen before or after death? Should it occur in steps, or all at once like you have shown?
try casting to a double in your operations that involve doubles and integers. For example
birthRate = (double)(birthRate / 100);
deathRate = (double)(deathRate / 100);
Sometimes programming languages will cast a double to an integer, which causes your numbers to be off.
Perhaps the number were rounded off?
I assume this is the case because I noticed you declared some variables in double but the end result is integer. Try to change the data type of the method
populationCalculator(), newPopulation and of course the returning values of the method populationCalculator() from int to double.

Multiplication with floats is wrong for some reason

SOk I edited out all the irrelevant information. Also I did some testing on a new file and it seems when you multiply two numbers that are being put in variables against each other it produces the wrong result. Like in my code the user is entering the length in feet first then in inches. The inches is then divided by 12 and added with feet. Also there getting rounded. Same goes for the width. Then when you multiply the length and width together it produces the wrong result.
Why is that? How do I fix it?
using namespace std;
void setdata();
int main(){
setdata();
return 0;
}
void setdata(){
int idnumber, lengthfeet, lengthinches, widthfeet, widthinches;
float costsqfoot, discount, lengthinchdec, widthinchdec, foot1, reallength, realwidth, arearoom;
foot1= 12;
cout << "What is length of room \t Feet: "; cin >> lengthfeet; cout << "\t \t \t Inches: "; cin >> lengthinches;
cout << "What is width of room \t Feet: "; cin >> widthfeet; cout << "\t \t \t Inches: "; cin >> widthinches;
cout << fixed << setprecision(2);
lengthinchdec = lengthinches / foot1; cout << lengthinchdec << endl; widthinchdec = widthinches / foot1; cout << widthinchdec;
reallength = lengthfeet + lengthinchdec; realwidth = widthfeet + widthinchdec; arearoom = (reallength * realwidth);
cout << endl;
cout << reallength << endl; cout << realwidth << endl;
cout << arearoom;
}
example
input for length feet:30
input for length inch: 5
input for width feet: 18
input for width inch: 11
Output for reallength is 30.42. The lengthinches is being divided by 12 so 5/12 is .42 when rounded up.
Output for realwidth is 18.92. The widthinches is being divided by 12 so 11/12 is .92 when rounded up.
The answer comes out 575.38.
It's supposed to come out 575.54
For your checking on the calculator, you're rounding up the intermediate results.
Your program isn't rounding the intermediate results, only the result of the multiplication.
575.38 is the correct answer!
Imperial units hell :)
multiplied it by hand and got
30 feet 5 inches * 18 feet 11 inches = 82 855 inches2
which is 575.38194444444 sqf
so... what is the problem?
and just for fun formatted the code and pushed it into CoLiRu with all variables set to double instead of float, just in case... http://coliru.stacked-crooked.com/a/2fcef984c5561159 and got the same result
Floating point calculations may be tricky. Values like the result of 5/12 aren't representable by a binary floating point number with a finite number of digits, so they are calculated and stored in float or a double types with a certain amount of rounding errors.
In some cases (like your particular example), one can avoid those errors (even if negligible in practice) using integer arithmetic instead.
Consider this snippet of code and how it deals with your problem:
#include <iostream>
#include <iomanip>
int main() {
using std::cout;
using std::cin;
constexpr int inches_in_one_foot = 12;
constexpr int square_inches_in_one_square_foot =
inches_in_one_foot * inches_in_one_foot;
// Please, note that in real code user input should be checked
int length_feet, length_inches, width_feet, width_inches;
cout << "What is the length of the room?\nFeet: ";
cin >> length_feet;
cout << "Inches: ";
cin >> length_inches;
cout << "What is the width of the room?\nFeet: ";
cin >> width_feet;
cout << "Inches: ";
cin >> width_inches;
// calculate the dimensions in inches
int length = length_inches + inches_in_one_foot * length_feet;
int width = width_inches + inches_in_one_foot * width_feet;
// the area is precisely calculated in square inches
int area = length * width;
int area_feet = area / square_inches_in_one_square_foot;
// note that this ^^^ is an integer division, or: 82855 / 144 = 575
int area_inches = area - area_feet * square_inches_in_one_square_foot;
cout << "\nArea: " << area_feet << " square feet and "
<< area_inches << " square inches.\n";
cout << "or : " << std::fixed << std::setprecision(2)
<< static_cast<float>(area) / square_inches_in_one_square_foot
<< " square feet.\n";
return 0;
}
Entering the values 30 5 18 11, it gaves the following output:
Area: 575 square feet and 55 square inches.
or : 575.38 square feet.
Note that in the second result, the decimal part doesn't represent 38 square inches, but 0.38 square feet, as a two figures approximation of the value 0.381944.

C++ power function with variables

#include <cstdlib>
#include <iostream>
#include <cmath>
using namespace std;
int main(int argc, char *argv[])
{
double amount, rate, time, interest, month;
interest = rate/(12.0*100);
month = (amount * rate)/1.0 -(1.0 + interest), pow(time*12);
cout << "What is the amount of the loan? $ ";
cin >> amount;
cout << "What is the annual percentage rate? ";
cin >> rate;
cout << "How many years will you take to pay back the loan? ";
cin >> time;
cout <<"\n-------------------------------------------------------\n";
cout << "Amount Annual % Interest Years Monthly Payment\n\n\n";
cout <<amount <<" " <<rate <<" " <<time << " " <<month;
cout <<"\n\n";
system("PAUSE");
return EXIT_SUCCESS;
}
I am getting an error here and am not sure exactly how to use the pow function properly. The formula according to the problem is:
Monthly payment = (loan amount)(monthly interest rate) / 1.0 - (1.0 + Monthly interest rate)^-(number of months)
Here is the line that I am having trouble with
month = (amount * rate)/1.0 -(1.0 + interest), pow(time*12);
Thanks for the help
std::pow accepts two arguments like so
pow (7.0,3)
So your code should be more like this
month = (amount * rate)/1.0 - std::pow( (1.0 + interest), 12);
Your code has other flaws as well, like you do calculation before you set the values.