How to break a for loop and convert integers? - c++

My program needs to calculates the cost for customers
to replace their carpet at $5 per yard for installation, various padding options,
carpet cost and total all rounded up to the nearest yard.
Padding is cost is based on:
Good - $3 per yard - 1-3year warranty
Better - $4 per yard 3-5 year warranty
Best- $5 per yard - 5-10 year warranty
Excellent - $7 per yard 10-20 year warranty
Operation:
Prompt User for number of rooms For each room:
Prompt length than width for each number of room
Calculate square feet a. convert square feet to square yards and round up b. square yards = yards required for room c. Calculate installation cost by square yard *$5
Prompt user to choose padding. a. Multiply padding cost by square yard of room
Prompt user for carpeting cost per sq yard of room: a. Calculate cost by multiplying input by squareyards required
Output total yards required
Output Installation cost
Output padding cost
Output carpet cost
Output total cost = + Installation + PAdding + Carpet
Grand total = cost of each room
******************/
I have 5 problems so far:
How to convert the integer padding choice to the cost of the quality
The floor loop will not break between rooms
When it displays the room number it starts at 0
How do I get the dollars to display to 2 decimal places?
How will I get the total of each rooms to store as doubles to get the grand total?
#include <iostream>
#include <iomanip>
#include <string>
#include <conio.h>
#include <string>
using namespace std;
const float INSTALL_COST = 5;
const float GOOD_PAD = 3;
const float BETR_PAD = 4;
const float BEST_PAD = 5;
const float EXC_PAD = 7;
const double SQU_FT_YD = 9;
int main ()
{
int padding, rooms, numreq, squareYards;
double length, width, squareFeet,priceSquareYard;
double paddingCost, installFee, totalCost, carpetCost;
//step 1:
cout << "Enter number of rooms: ";
cin >> numreq;
cout << endl;
//Step 2
cout << "Enter length of room: ";
cin >> length;
cout << endl;
cout << "Enter width of room: ";
cin >> width;
cout << endl;
//step 3
cout << "Select quality of padding:<1-4> ";
cout << "\n1. Good - $3 per yard - 1-3 year warranty \n2. Better - $4 per yard 3-5 year warranty \n3. Best- $5 per yard - 5-10 year warranty \n4. Excellent - $7 per yard 10-20 year warranty: ";
cin >> padding;
cout << "Enter price of carpeting per square yard of room: ";
cin >> priceSquareYard;
//step3
for(int x = 0; x < numreq; x++)
{
squareFeet = length * width;
squareYards = ((squareFeet / SQU_FT_YD) + 0.5);
if (squareYards > 0)
squareYards++;
installFee = squareYards * INSTALL_COST;
carpetCost = priceSquareYard * squareYards;
paddingCost = squareYards * padding;
totalCost = carpetCost + installFee + paddingCost;
cout << "\n Room " << x << " Yards Required = " << squareYards;
cout << "\n Room " << x << " Installation = $" <<installFee;
cout << "\n Room " << x << " Padding Cost = $" << paddingCost;
cout << "\n Room " << x << " Carpet Cost = $" << carpetCost;
cout << "\n Room " << x << " Total Cost = $" << totalCost;
}
_getch();
return 0;
}

To get totals within loops, simply store a variable outside of the loop, start it at 0, and increment it within the loop whenever necessary.
And you can use break; to break out of the loop completely. Also, if you need this, continue; will let you stop the current iteration and jump straight to the next iteration of your for-loop.
And for number 4, check this out:
NumberFormat/DecimalFormat treats certain floating-point values as longs instead of doubles

Related

How to handle floating point comparisons in C++ mathematical expressions therefore rounding errors can be handled?

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;
}

The rand() function in C++ is giving a number outside the range

So I'm trying to write a story about Jordan paying bills and stuff. I used a rand function to find a random number for his salary 3.5k - 4.5 and bills 700 -1.5k. I believe I got the formula right but usually, it generates a number outside that area. Below is the code and result.
{
srand(time(NULL));
cout << fixed;
cout << setprecision(2);
float money = 9000;
int minbill = 700;
int maxbill = 1500;
int minsal = 3500;
int maxsal = 4500;
float rent = 3000;
cout << "[Jordan's Balance: Gp" << money << "]\n\n";
cout << "Jordan's rent costs Gp" << rent <<".\n";
float bill = (rand()%maxbill-minbill+1)+minbill;
cout << "Jordan's bills costs Gp" << bill << ".\n";
float totalb = rent + bill;
cout << "Jordan needs to pay a total of Gp" << totalb << "\n\n";
float sal = (rand()%maxsal-minsal+1)+minsal;
cout << "Jordan received a salary of Gp" << sal << "!!\n";
money = money + sal;
cout << "[Jordan's Balance: Gp" << money << "]\n\n";
}
I expect Jordan's bills to be around 700-1.5k and his salary 3.5k-4.5k but it gives me a number below that.
Jordan's rent costs Gp3000.00.
Jordan's bills costs Gp133.00.
Jordan needs to pay a total of Gp3133.00
Jordan received a salary of Gp1906.00!!
[Jordan's Balance: Gp10906.00]
(rand()%maxbill-minbill+1) is wrong.
It's possible that rand()%maxbill will be less than minbill. You need to use rand() % (maxbill - minbill + 1).
float bill = rand() % (maxbill-minbill+1) + minbill;
Similarly, use
float sal = rand() % (maxsal-minsal+1) + minsal;

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.

Looping functions for a number of times

So I am trying to get this program to allow the user to input their data 4 times. I want the program to call each function until the user enters them for the 4th time, but it is not letting me and just stops at the 2nd attempt. Can someone help me with this problem? Thanks!
Output:
Enter the crop name:
Corn
Enter cost, yield, price per bushel, and increase data:
5
5
5
5
Minimum Profit Maximum Profit Average Profit
Corn $20000.00 $145000.00 $82500.00
Enter the crop name:
Enter cost, yield, price per bushel, and increase data:
Peas
Minimum Profit Maximum Profit Average Profit
$20000.00 $145000.00 $82500.00
Enter the crop name:
Enter cost, yield, price per bushel, and increase data:
Minimum Profit Maximum Profit Average Profit
$20000.00 $145000.00 $82500.00
Enter the crop name:
Enter cost, yield, price per bushel, and increase data:
Minimum Profit Maximum Profit Average Profit
$20000.00 $145000.00 $82500.00
Enter the crop name:
Enter cost, yield, price per bushel, and increase data:
Minimum Profit Maximum Profit Average Profit
$20000.00 $145000.00 $82500.00
Press any key to continue . . .
enter code here
Program:
#include <iostream>
#include<iomanip>
#include<string>
#define ACRES 1000;
using namespace std;
//Function prototypes.
void getData(string*, float*, int*, float*, float*);
void calculate(float, int, float, float, float*, float*, float*);
void printResults(string, float, float, float);
int main()
{
string name;
float CostPerAcre, increase, bushel, MinNP, MaxNP, AvgProfit2, bestcrop;
int yield;
for(int i = 0; i <= 4; ++i)
{
getData(&name, &CostPerAcre, &yield, &bushel, &increase);
calculate(CostPerAcre, yield, bushel, increase, &MinNP, &MaxNP, &AvgProfit2);
printResults(name, MinNP, MaxNP, AvgProfit2);
}
//cout << endl << "Old MacDonald, you should plant " << bestCrop << endl << endl;
return 0;
}
// This function allows the user to input their data.
void getData(string *cropname, float *costpa, int *bpa, float *dpb, float *dpbincrease)
{
cout << "Enter the crop name: " << endl;
getline(cin, *cropname);
cout << "Enter cost, yield, price per bushel, and increase data: " << endl;
cin >> *costpa >> *bpa >> *dpb >> *dpbincrease;
}
// This function uses the data to calculate the projected range of net profit and the average net profit for each crop.
void calculate(float costpa, int bpa, float dpb, float dpbincrease, float *MnNP, float *MxNP, float *AvgProfit)
{
float MnGP, MxGP;
float costofCrop = costpa * ACRES;
MnGP = (bpa * dpb ) * ACRES;
MxGP = MnGP + (MnGP * dpbincrease);
*MnNP = (MnGP)-costofCrop;
*MxNP = (MxGP)-costofCrop;
*AvgProfit = (*MxNP + *MnNP) / 2;
}
// This function displays the minimum profit, maximum profit, and average profit.
void printResults(string cropname, float MnNP, float MxNP, float AvgProfit)
{
cout << setw(25) << right << "Minimum Profit" << setw(20) << right << "Maximum Profit" << setw(20) << right << "Average Profit" << endl;
cout << cropname << setw(5) << right << setprecision(2) << fixed << '$' << MnNP << setw(10) << right << setprecision(2) << fixed << '$' << MxNP << setw(10) << right << setprecision(2) << fixed << '$' << AvgProfit << endl;
}
In the getData function, instead of using getline, do:
cin >> *cropname;
Why? Like they said in a similar question, "If you're using getline after cin >> something, you need to flush the newline out of the buffer in between".
insert that after reading from console.
cin.clear();
fflush(stdin);
or
cin.flush();
or
cin.ignore(INT_MAX);
depends on the system you are running it
Check This for more Info

Calculation Problem C++

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.