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
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'm getting some odd outputs when running this program. Any suggestions? Pardon the mess. Typed it up in a hurry. This is the guidelines for the assignment.
Write a program that asks for the user’s height, weight, and age, and
then computesclothing sizes according to the formulas:
1.Hat size = weight in pounds divided by height in inches and all multiplied by 2.9
2.Jacket size (chest in inches) = height times weight divided by 288 and then adjusted by adding 1/8 of an inch for each 10 years over the age of 30. (Note that the adjustment only takes place after a full 10 years. Thus, there is no adjustment for ages 30 through 39, but 1/8 of an inch is added for age 40.)
3.Waist in inches=weight divided by 5.7 and then adjusted by adding 1/10 of an inch for each 2 years over age 28. (Note that the adjustment only takes place
after a full 2 years. Thus, there is no adjustment for age 29, but 1/10 of an inch is added for age 30.)
#include <iostream>
using namespace std;
double hat(double,double);
double jacket(double,double,int);
double waist(double,double,int);
int main ()
{
double height, weight;
int age;
char answer;
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
do
{
cout<< "Enter the customer's height in inches: ";
cin>>height;
cout<< "Enter the customer's weight in pounds: ";
cin>>weight;
cout<< "Enter the customer's age: ";
cin>>age;
cout << cout<< "\tYour Hat size: " << cout << "\tYour Jacket size: "< cout << "\tYour Waist size: "<< cout<< "Would you like to continue (y/n)? ";
cin>>answer;
}while(toupper(answer) == 'Y');
return 0;
}
double hat(double weight ,double height)
{
return ((weight/height) * 2.9);
}
double jacket(double height,double weight,int age)
{
double size;
int j;
if (age>=30)
{
if((age % 10) !=0)
age = age-(age%10);
j= (age-30)/10;
size =((height * weight) / 288)+((1.0/8)*j);
}
else
size =((height * weight) / 288);
return size;
}
double waist(double height,double weight,int age)
{
double size2;
int k;
if(age >= 28)
{
if((age % 2) !=0)
age = age-(age%2);
k = (age-28)/2;
size2 = (weight/(5.7))+( (1.0/10)*k);
}
else
size2 = weight / (5.7);
return size2;
}
Your final cout << line in the do loop is piping cout to cout, instead of your answer to cout. Not to mention there's a < in there after jacket size instead of a <<
cout << cout<< "\tYour Hat size: " << cout << "\tYour Jacket size: "< cout << "\tYour Waist size: "<< cout<< "Would you like to continue (y/n)? ";
You never even tried to do the calculation, so you have no answer to print.
Instead I see a lot of cout << cout in your code. Trying to print cout itself doesn't turn out well. What happens is that iostreams don't know how to print an output stream, however in old versions of C++, cout has an implicit conversion to a pointer, and a stream knows how to display that. So you are seeing the pointer equivalent to cout.
You should enable C++11 (or later) support in your compiler. Then cout won't have an implicit conversion to void*, and the compiler will detect mistakes like this.
you just need to replace your cout line with this line of code
cout<< "\tYour Hat size: " << hat(weight ,height) << "\tYour Jacket size: "<< jacket( height, weight, age) << "\tYour Waist size: "<< waist( height, weight, age)<< "\n \nWould you like to continue (y/n)? ";
I've been working on an assignment that calculates the total profit/loss for multiple stock sales via a looping function with information inputted by user for each stock sale. I did a thorough amount of googling to no avail. I was able to get the function working within the loop but I have not been able to figure out how to add the profit/loss from multiple sales - instead only displaying profit/loss for each individual function call. My function's algorithm checks out if you manually add the totals for each sale, just unclear on how to find the sum of multiple function calls.
Here is the sample data I'm suppose to enter that should display the total profit of $3324.00:
sale numberOfShares salePrice salesCommission purchasePrice purchaseCommission
1 25 15 7.50 5 2.50
2 100 2.50 12 1.75 8
3 1000 5.10 51 2 20
And my code thus far:
#include <iostream>
#include <iomanip>
using namespace std;
// Function prototype
double stockProfitFunction(double NS, double PP, double PC, double SP, double SC);
// Main Function
int main()
{
// Format output
cout << fixed << setprecision(2);
// Initialize variables
double profit,
numberOfShares,
salePrice,
saleCommission,
purchasePrice,
purchaseComission;
int numberOfSales;
// Get # of sales from user
cout << "Multiple Stock Profit Calculator\n--------------------------------\n\n";
cout << "How many sales do you wish to enter?: ";
cin >> numberOfSales;
cout << endl;
// Perform function in loop for number of sales
for (int i = 1; i <= numberOfSales; i++)
{
system("cls"); // Clears screen
cout << "Multiple Stock Profit Calculator\n";
cout << "(Currently entering stock sale #" << i << ")\n----------------------------------\n";
// Get information from user
cout << "Enter number of shares: ";
cin >> numberOfShares;
cout << "Enter sale price: ";
cin >> salePrice;
cout << "Enter sales commission: ";
cin >> saleCommission;
cout << "Enter purchase price: ";
cin >> purchasePrice;
cout << "Enter purchase commission: ";
cin >> purchaseComission;
//Calcualtes profit with function
profit = stockProfitFunction(numberOfShares, purchasePrice, purchaseComission, salePrice, saleCommission);
// Display "profit" or "loss" depending on positive or negative value returned by function
if (profit >= 0)
{
cout << "\n-----------------------\n";
cout << "You earned a profit of: $" << profit << endl;
cout << "(Press enter to input next sale)";
cin.get();
cin.get();
}
else
{
cout << "\n-----------------------\n";
cout << "You had a loss of: $" << profit << endl;
cout << "(Press enter to input next sale)";
cin.get();
cin.get();
}
}
return 0;
}
// Stock Profit Function, returns profit
double stockProfitFunction(double NS, double PP, double PC, double SP, double SC)
{
return ((NS * SP) - SC) - ((NS * PP) + PC);
}
Thanks for taking a look!
Initialize a variable to zero.
Each time you calculate a profit, add it to that variable.
Where desired, output the value of that variable.
By the way:
system("cls"); // Clears screen
That's a very bad habit to get into. Maybe on your machine, cls clears the screen, but you have no way to know what the cls command might do on someone else's machine. (On mine, there is no command called cls, the clear screen command is clear.) Unless you absolutely have no choice, you should strongly avoid using system in your C++ code.
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
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.