I'm really new to C++, and this is homework. I don't understand what's going on. When I run this, everything works fine if I put in 60000 for current salary and .05 for pay increase, but if I put in something like 52000 for current salary and .23 for pay increase, then the retroactive pay comes out as 5982.00 instead of 5980.00. Is it something to do with the decimals or something? I don't really know. Thanks in advance.
// Variables
char fullName[30]; // The user's full name - INPUT
int currentAnnual; // The users's current annual salary - INPUT
float percentIncrease; // The percent increase due on the
// current annual salary - INPUT
// The retroactive pay
float retroactive;
// The new monthly salary based on the pay increase and the new salary
float monthlySalary;
// The new salary the user should receive based on their old salary
// and their pay increase
float newSalary;
for(int lcv = 1; lcv <= 3; lcv++)
{
// INPUT
cout << "What is your full name? ";
cin.getline(fullName, 30);
cout << "What is your current salary? ";
cin >> currentAnnual;
cout << "What is your pay increase (please input percentage in"
"decimal format)? ";
cin >> percentIncrease;
// PROCESSING
newSalary = (currentAnnual * percentIncrease) + currentAnnual;
monthlySalary = newSalary / 12;
retroactive = (monthlySalary - (currentAnnual / 12)) * 6;
// OUTPUT
cout << endl;
cout << fullName << "'s Salary Information\n";
cout << left << setw(15) << "New Salary" << setw(19) << "Monthly Salary"
<< "Retroactive Pay\n";
cout << setprecision(2);
cout << fixed;
cout << right << setw(10) << newSalary << setw(19) << monthlySalary
<< setw(20) << retroactive << endl << endl;
cout << "<Press enter to continue>";
cin.ignore(100, '\n');
cin.ignore(1000, '\n');
cout << endl;
}
currentAnnual / 12
The division of two integers in C is an "integer division" (it gives an integer), and I think you dont want that. One solution is to change it to currentAnnual / 12.0. Anyway, it's important that you understand what is happening here.
Change currentAnnual / 12 to currentAnnual / 12.0 to force a floating-point calculation to be done. Otherwise, that part of the computation will be rounded off to the nearest integer below.
You should do monthlySalary = newSalary / 12.0; instead of monthlySalary = newSalary / 12;
so you have to specify that you want to divide on float number. Otherwise result will be integer. For example 125./12 = 10 but 125./12. = 10.41(6). And of course you get wrong results.
Try to add .0 or just . to all your constants.
Floating point calculations are not as accurate as you might expect. Try replacing float with double in the above code (double is a "double-precision floating-point number"; it can store many more values than a float, and is much more accurate).
Also, order of operations is sometimes significant, so you may want to re-order the retroactive calculation to something like
6 * monthlySalery - currentAnnual / 0.5;
and try other combinations to see what works best.
Related
Let me explain little further. I am writing a code to calculate the amount of water in swimming pool after filling it for some time at the filling rate.
Input taken is length, width, depth in foot, time to fill the pool as timeToFillPool in seconds, water filling rate in pool as fillingRate in in US Gallons/minute, amount of water already in the pool as poolCurrWaterAmount in US Gallons.
From this information I calculated total pool water capacity, totalPoolCapacity, by multiplying length, width and depth and converting it to US Gallons.
I asked the user that how much water is already in the pool and then calculated and shown user appropriate messages like water can be filled or not if the pool is already full or water filled in given time will exceed pool capacity?
I am assuming all values input are positive or equal to zero if allowed to be zero.
#include <iostream>
#include <iomanip>
#include <cmath> //for fabs() functions
using namespace std ;
int main()
{
double timeToFillPool ;
double length, width, depth, fillingRate ;
double poolCurrWaterAmount, totalPoolCapacity ;
const double CUBIC_FOOT_TO_USGALLON = 7.48052 ; //i.e. 1 cubic foot = 7.48052 US Gallon
//setting tolerance value for comparing floating point numbers to 1/10000
//any thing less will be considered zero
const double EPSILON = 0.0001 ;
//preparing the output stream to print floating numbers in decimal
//form with precision to print two digits after decimal point
cout << fixed << setprecision(2);
cout << "Please enter swimming pool's dimensions,capacity,fill rate & drain rate information.\n";
cout << "Enter Length in foot : " ;
cin >> length ;
cout << "Enter width in foot : " ;
cin >> width ;
cout << "Enter depth in foot : " ;
cin >> depth ;
cout << "Enter filling rate of water in US Gallon/min : " ;
cin >> fillingRate ;
//calculating totalPoolCapacity in US Gallon
totalPoolCapacity = length * width * depth * CUBIC_FOOT_TO_USGALLON ;
cout << "\n\nTotal pool capacity = " << totalPoolCapacity << " US Gallon." ;
cout << "\n\nPlease enter current amount of water in pool in US Gallon to " ;
cout << "\nfill the pool according to filling rate for the specific amount of time in minutes : " ;
cin >> poolCurrWaterAmount ;
//to check minimum and maximum range of current amount of water.
while( !(poolCurrWaterAmount >= 0.0 && poolCurrWaterAmount <= totalPoolCapacity ) )
{
cout << "\nYou have entered in-valid value for current amount of water!"
<< "\nEnter current amount of water value from 0 to maximum capacity of pool "
<< setw(10) << totalPoolCapacity << " in US Gallon : " ;
cin >> poolCurrWaterAmount ;
}
cout << "\nPlease enter time in minute to fill water in pool : " ;
cin >> timeToFillPool ;
//Calculations and message displayed are on the basis of whether the filling water
//will cause overflow of water after filling the pool or not.
//managing floating point eqaulity poolCurrWaterAmount == totalPoolCapacity
//setting the tolerance value EPSILON to 1/10000 = 0.0001 of a US Gallon
if ( fabs(poolCurrWaterAmount - totalPoolCapacity) < EPSILON)
{
cout << "\n\nPool is Full. Water cannot be added." ;
cout << "\nTotal water in pool is " << setw(10) << totalPoolCapacity << " US Gallon." ;
}
else if (fillingRate * timeToFillPool > (totalPoolCapacity - poolCurrWaterAmount) )
{
//case to check that time entered for filling water will cause overflow of water or not
cout << "\n\nWarning! Pool will be overflowed with water! No water added!" ;
cout << "\nCurrent amount of water in pool = "
<< setw(10) << poolCurrWaterAmount << " US Gallon." ;
cout << "\nMaximum time required to completely fill the pool at\nfilling rate of "
<< setw(10) << fillingRate << " US Gallon/min is "
<< setw(10) << ( (totalPoolCapacity - poolCurrWaterAmount) / fillingRate ) << " minute." ;
}
else //case where time entered for filling water will not cause overflow of water in pool
{
cout << "\n\nCurrent amount of water in pool = "
<< setw(10) << poolCurrWaterAmount << " US Gallon." ;
cout << "\nAfter filling "
<< setw(10) << (fillingRate * timeToFillPool) << " US Gallon at filling rate of "
<< setw(10) << fillingRate << " US Gallons/min for "
<< setw(10) << timeToFillPool << " minute\nthe new amount of water in pool is "
<< setw(10) << ( poolCurrWaterAmount + fillingRate * timeToFillPool ) << " US Gallon." ;
}
}
//end of main function
this is the ouput of the program: -
***********************************
Please enter swimming pool's dimensions,capacity,fill rate & drain rate information.
Enter Length in foot : 3
Enter width in foot : 2
Enter depth in foot : 2
Enter filling rate of water in US Gallon/min : 4
Total pool capacity = 89.77 US Gallon.
Please enter current amount of water in pool in US Gallon to
fill the pool according to filling rate for the specific amount of time in minutes : 89.77
You have entered in-valid value for current amount of water!
Enter current amount of water value from 0 to maximum capacity of pool 89.77 in US Gallon :
************************************************************************************************
The problem is that the internal value stored in totalPoolCapacity is 89.76624
and due to setprecision(2) it rounds of the value to 89.77 so when I enter 89.77 it doesn't
accept it as a right value although it should be right value according to display message.
I don't want to show whole value to user.
Also please explain how to handle this calculation with setprecision(2)
(totalPoolCapacity - poolCurrWaterAmount) / fillingRate
and what will be good EPSILON value to compare floating point numbers.
therefore time calculated and shown to user will not effect the overall calculation with rounding effects. That is what user sees, the program behaves according to that by manipulating internal representation of floating point numbers and their rounding off effects.
You should never do a floating point comparison like poolCurrWaterAmount <= totalPoolCapacity.
Instead you should do (poolCurrWaterAmount - totalPoolCapacity) < epsilon.
In your case, epsilon should be 0.005.
In general, for an equality operator, epsilon could be as small as
DBL_EPSILON.
For a deep-dive into this topic, including more rigorous algorithms, see comparing-floating-point-numbers-2012-edition.
One thing you could do is call std::fesetround(FE_DOWNWARD); so that your displayed numbers get rounded downwards rather than upwards. That would make it so that when the user re-enters the rounded value he saw in your output, the entered value is slightly less than the actual capacity of the pool, rather than slightly more, and would therefore avoid triggering your error message.
Or, if you don't like that approach, you could alternatively just set poolCurrWaterAmount = std::min(poolCurrWaterAmount, totalPoolCapacity); instead of emitting an error message, so that if the user enters a value greater than the pool's capacity, it is treated as if he entered a value equal to the pool's capacity.
For the first question:
The problem is that the internal value stored in totalPoolCapacity is
89.76624 and due to setprecision(2) it rounds of the value to 89.77 so when I enter 89.77 it doesn't accept it as a right value although it
should be right value according to display message. I don't want to
show whole value to user.
you can try set the poolCurrentWaterAmount to totalPoolCapacity if the user enters a value that is equal to the rounded value of totalPoolCapacity, for example:
#include <iostream>
#include <iomanip>
#include <sstream>
double round_double_value(double val, int prec) {
std::stringstream strstream;
strstream << std::fixed << std::setprecision(prec) << val;
double result;
strstream >> result;
return result;
}
int main()
{
const double CUBIC_FOOT_TO_USGALLON = 7.48052 ;
const double EPSILON = 0.0001 ;
double length = 3.0;
double width = 2.0;
double depth = 2.0;
double fillingRate = 4.0;
double totalPoolCapacity = length * width * depth * CUBIC_FOOT_TO_USGALLON ;
int out_precision = 2;
std::cout << std::fixed << std::setprecision(out_precision);
std::cout << "Total pool capacity = " << totalPoolCapacity << " US Gallon.\n" ;
double poolCurrWaterAmount = 89.77;
std::cout << "You entered current pool water amount = " << poolCurrWaterAmount << '\n';
if ((poolCurrWaterAmount > totalPoolCapacity)
&& (poolCurrWaterAmount == round_double_value(totalPoolCapacity, out_precision)) ) {
// Assume the user meant to input the maximum..
poolCurrWaterAmount = totalPoolCapacity;
}
if( !(poolCurrWaterAmount >= 0.0
&& poolCurrWaterAmount <= totalPoolCapacity ) )
{
std::cout << "You have entered in-valid value for current amount of water!\n";
return(1);
}
return 0;
}
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.
For my currency calculator, I need to add 3 different types of functions-
1) enterCostUSD (I enter the cost in USD)
2) convertCost (convert the cost from USD to, say, rupees)
3) displayOutput (display the output of the new cost)
I have total 10 cases. How do I add the functions so that they apply to all
10 cases?
Do I need to add them in the middle of each case?
This is one of the case, Do I need to do it in this way or there is any better way?
case 1: //Finding cost in Altairian Dollars
cout << "Enter the cost in US Dollars: ";
cin >> enterCostUSD;
altairianDollars = enterCostUSD*0.72
cout << "$" << enterCostUSD << " is equal to " << altairianDollars
cout << "Thank You for using the Currency Calculator!" << endl;
break;
What I understood from your question is you have 10 cases where you are trying to convert the currency. So for that you have to create 10 cases like you mentioned in your question.
If any of the functionality which is common to all of your cases you can keep it in a function and call it from each cases.
Here printing output and converting currency are the functionality which can be put separate.
For eg:
case 2: //Finding cost in Rupee
CostUSD=enterUSDCost();//function 1
conversion_rate=63.5;//for rupee
Rupee = convertCost(CostUSD,conversion_rate);//function2
displayOutput(enterCosstUSD,Rupee,"Rs");//function 3
break;
These three functions need to be out of the scope of your main function, these are three separate function.
float enterCostUSD()
{
float USD_cost;
cout << "Enter the cost in US Dollars: ";
cin >> USD_cost;
return USD_cost;
}
float convertCost(float USD, float rate)
{
return USD*rate;
}
void displayOutput(float enterCostUSD, float Rupee,string conversion_currency){
cout << "$" << enterCostUSD << " is equal to " << Rupee <<conversion_currency ;
cout << "Thank You for using the Currency Calculator!" << endl;
}
If you like to develop better understanding of switch case follow this link
I Have this code to find out the total purchase price of some numbers and i need to know how to round the numbers to only 2 decimal places.
#include <iostream.h>
#include <cstdlib.h>
#include <string.h>
int main() {
float sale_price;
float tax_rate;
float discount_rate;
system("cls");
system("color 07");
cout << "\n\nWelcome to the second version of my total purchase price calculator!\n";
cout << "How much did your recently purchased item cost? ";
cin >> sale_price;
cout << "What is the tax rate in your area? ";
cin >> tax_rate;
cout << "What was the discount rate, if any (if none, just put down 1) ";
cin >> discount_rate;
float tax = sale_price*(tax_rate/100);
float discount = sale_price*(discount_rate/100);
float total_price = sale_price + tax - discount;
cout << "The total price of your item is $"<<total_price<<" with $"<<tax<<" tax minus $"<<discount<<" due to discount.\n";
cout << "Would you like a reciept? y or n. ";
string answer;
End:
cin >> answer;
if (answer == "y") {
goto Reciept;
}
else if (answer == "n") {
return 0;
}
else {
cout << "Try another answer\n";
goto End;
}
Reciept:
system("cls");
system("color 70");
cout << "\xda\xc4\xc4\xc4\xc4\xc4\xc4\xc4\xc4\\xc4\xc4\xc4\xc4\xc4\xc4\xc4\xc4\xbf\n";
}
this usually gives me 4 decimal places just FYI
Round to 2 decimals: int((n * 100.0) + 0.5) / 100;
Round to 3 decimals: int((n * 1000.0) + 0.5) / 1000;
etc.
The easy way is to use setprecision:
std::cout << "The total price of your item is $"
<< std::setprecision(2) << total_price ...
This will occasionally get things wrong. A better solution is to use an improved rounding function that is not a part of the standard (e.g., How does Excel successfully Rounds Floating numbers even though they are imprecise?). An even better solution is to implement your own fixed point arithmetic algorithm so as to avoid this problem entirely. You can still go one better than that: Use a fixed point arithmetic package that someone else has already written and tested to the nth degree.
You should use Iomanip's setprecision:
setprecision reference
When you output with cout, use the setprecision() operator.
cout << fixed;
cout << setprecision(2) << sale_price*(tax_rate/100);
Do
cout.precision(2);
cout << fixed;
before you output the floats.
Could some one help me with this?
I've racked my head over an hour and I can't get it to work.
This is in C++ and I've been learning for a little bit but I'm still new...
int main()
{
double rate, amount,time, S;
cout << "Insert the time of the super: ";
cin >> time;
cout << "Insert the rate (as a decimal, eg 1% AKA 101% = 1.01): ";
cin >> rate;
cout << "Insert the amount $: ";
cin >> amount;
S =("amount * (rate ^ time - 1)", pow(rate,time));
cin >> S;
cout << "The total amount is: " << "S /(rate - 1)" << endl;
system("PAUSE");
return 0;
}
i dont get a compile error but i can never get an answer from it
You "never get a result" because you're setting S to the result of pow with comma operator weirdness then assigning to it again with the line
cin >> S;
which is waiting for you to input another number.
You have two main problems. Here is the updated code with comments on the altered parts:
int main()
{
double rate, amount,time, S;
cout << "Insert the time of the super: ";
cin >> time;
cout << "Insert the rate (as a decimal, eg 1% AKA 101% = 1.01): ";
cin >> rate;
cout << "Insert the amount $: ";
cin >> amount;
S = amount * pow(rate, time - 1); // take away the quotes and don't make pow seperate
cout << "The total amount is: " << (S /(rate - 1)) << endl; // do the calculation and output it
system("PAUSE");
return 0;
}
Remember that things inside quotes "like this" are string literals, so "4 * 4" is a string but 4 * 4 (see the absence of quotes) does multiplication which yields the number 16.
I don't think you should assign values to S the way you are doing it. S is declared as double and you are assinging a string to it initially. And when you output the result you are also enclosing the calculation in quotes. You should simply cout << S / (rate-1); // without quotes or cout will simply output the string