Unable to make program calculate correctly - c++

I am trying to make a program which does a very basic calculation, but for some reason i can't get the code right. It is supposed to calculate the miles per gallon for one trip. You can then add this info multiple times (for different trips) and for each time it should calculate the total miles per gallon (i.e. the average miles per gallon of all the trips). This is the code:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int counter = 1;
double milePerRe, milePerTo = 0, x, y;
cout << "Enter the miles used (-1 to quit): ";
cin >> x;
cout << "Enter gallons: ";
cin >> y;
while (x != -1)
{
milePerRe = x/y;
milePerTo += milePerRe;
milePerTo /= counter;
cout << "MPG this tankful: " << setprecision( 6 ) << fixed << milePerRe;
cout << "\nTotal MPG: " << setprecision( 6 ) << fixed << milePerTo << endl << endl;
counter++;
cout << "Enter the miles used (-1 to quit): ";
cin >> x;
if (x != -1)
{
cout << "Enter gallons: ";
cin >> y;
}
}
system("pause");
return 0;
}
When I run the program and say I enter 10 on the miles and 1 on the number of gallons the first time and the second time, everything works fine. Then if i do it again a third time the calculations begin to become incorrect.

You can not calculate average of averages the way you do it. In your code you are dividing by the counter EACH iteration, while you should divide it only at the end.
Best way to do what you need is something like this:
...
double totalMiles = 0;
double totalGallons = 0;
...
while (x != -1)
{
milePerRe = x/y;
totalMiles += x;
totalGallons += y;
milesPerTo = totalMiles / totalGallons;
...
However, if your task was to explicitly calculate the average of trips (not the average of miles/gallons), you would need to introduce another variable, like this:
...
double currentMilesPerTo;
...
while (x != -1)
{
milePerRe = x/y;
milePerTo += milePerRe;
currentMilesPerTo = milePerTo/counter;
....
cout << "\nTotal MPG: " << currentMilesPerTo;
...

the value of x and y are not being updated properly i guess.after every iteration try to make x and y to zero.
hope it works this way
TNQ

Related

C++ Program using functions

I'm writing a program for my C++ class I've complete the program. but it won't compile. I'm new to programming so I don't really know what I'm doing wrong. If there is anyone on here that can point me in the right direction. Please help me!
Prompt Description:
Write a C++ program to calculate free estimate for carpet and furniture cleaning of residential and business customers. The program continues until end of file is reached.
Fro residential customers, specify and update number of small couches ($50 each), large couches ($80 each), rooms ($70 each) and steps ($5 each) until exit is selected. the bill is calculated based on the number of items. If the amount is more than 500 dollars, a discount of 10% is applied to the bill. Then the customer is offered to select from an installment of 1,2,3, or 4 or press 0 to exit. Based on an installment option, the bill is increased slightlenter code herey, and each installment amount is calculated.
For business customers, ask the user to enter the amount of square footage and then the bill is calculated at .45 per square foot.
Here is the code:
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int exit = 0;
int smallcouches = 1;
int largecouches = 2;
int rooms = 3;
int steps = 4;
const float SMALL_COUCH = 50.0;
const float LARGE_COUCH = 80.0;
const float ROOMS = 70.0;
const float STEPS = 5.00;
const float PER_SQUARE_FOOT = 0.45f;
const float DISCOUNT_QUALIFIED = 500.0;
const float DISCOUNT = 0.10f;
const int ONE = 1;
const int TWO = 2;
const int THREE = 3;
const int FOUR = 4;
const float RATEONE = 0.0f;
const float RATETWO = 0.0535f;
const float RATETHREE = 0.055f;
const float RATEFOUR = 0.0575f;
float billAmount;
float ResidentialEstimate(float SMALL_COUCH, float LARGE_COUCH, float ROOMS, float STEPS, float DISCOUNT_QUALIFIED);
void GetResidentialItems(int& smallcouches, int& largecouches, int& rooms, int& steps);
void InstallmentPlan(float billAmount);
void BusinessEstimate(float PER_SQUARE_FOOT);
int main()
{
cout << fixed << showpoint << setprecision(2);
int customerType, residential_customer, business_customer;
char B, b, R, r;
residential_customer = R || r;
business_customer = B || b;
cout << "Enter customer type: R, r (Residential) or B, b (Business): ";
cin >> customerType; //Enter customer type
cout << endl;
while (cin) //While there is input to read
{
if (customerType == R || customerType == r) //if residential customer
{
ResidentialEstimate(SMALL_COUCH, LARGE_COUCH, ROOMS, STEPS, DISCOUNT_QUALIFIED); // call function ResidentialEstimate
InstallmentPlan(billAmount); // all function Installmentplan
}
else if (customerType == B || customerType == b) //else if business customer
{
BusinessEstimate(PER_SQUARE_FOOT); //call function BusinessEstimate
}
cout << "Enter customer type: R, r (Residential) or B, b (Business): ";
cin >> customerType; // Enter cutomer type
cout << endl;
}
return 0;
}
float ResidentialEstimate(float SMALL_COUCH, float LARGE_COUCH, float ROOMS, float STEPS, float DISCOUNT_QUALIFIED)
{
GetResidentialItems(smallcouches, largecouches, rooms, steps); //Call function GetResidentialItems to get items to clean
billAmount = (SMALL_COUCH + LARGE_COUCH + ROOMS + STEPS); //Calculate the bill amount
if (billAmount > 500) //if bill amount is more than 500 dollars
{
DISCOUNT_QUALIFIED = billAmount * 0.10f;
billAmount = billAmount - DISCOUNT_QUALIFIED; //Apply a discount of 10% to the bill amount
}
return billAmount; //return bill Amount
}
void GetResidentialItems(int& smallcouches, int& largecouches, int& rooms, int& steps)
{
int count;
int choice = smallcouches || largecouches || rooms || steps;
//Ask user to select an item to update or press 0 to exit
cout << "0. Exit, 1. Small Couches, 2. Large Couches, 3. Rooms, 4. Steps " << endl;
cout << "Enter one of the above choices: ";
cin >> choice;
cout << endl;
while (choice > 0) //while user hasn't pressed 0
{
choice = count;
cout << "Please enter the number of " << choice; //ask the user to enter a number from the item selected
cin >> count;
cout << endl;
//Show the current selections and numbers
cout << "Current selections: " << count << " Small Couches, " << count << " Large Couches, " << count << " Rooms, " << count << " Steps.";
//Ask user to select an item to update or press 0 to exit
choice = 0;
count = 0;
cout << "0. Exit, 1. Small Couches, 2. Large Couches, 3. Rooms, 4. Steps " << endl;
cout << "Enter one of the above choices: ";
cin >> choice;
cout << endl;
}
}
void InstallmentPlan(float billAmount)
{
int num;
int installment = 0;
int bill = 0;
//Ask user to select number of installments or 0 to exit
cout << "Please enter the desired number of instalments (1, 2, 3, or 4) or 0 to exit : ";
cin >> num;
cout << endl;
while (num > 0) //while user hasn't pressed 0
{
//calculate the installments
if (num == 1)
installment = billAmount;
else if (num == 2)
{
bill = billAmount * 0.0535f;
installment = bill / num;
}
else if (num == 3)
{
bill = billAmount * 0.055f;
installment = bill / num;
}
else if (num == 4)
{
bill = billAmount * 0.0575f;
installment = bill / num;
}
cout << "With " << num << " installment your bill of " << billAmount << " will be worth " << bill << "." << endl;
cout << "Each installment will be worth " << installment << endl;
//Ask user to select number of installments or 0 to exit
cout << "Please enter the desired number of instalments (1, 2, 3, or 4) or 0 to exit : ";
cin >> num;
cout << endl;
}
}
void BusinessEstimate(float squarefootage)
{
//Ask user for the square footage
cout << " Enter the approximate square footage: ";
cin >> squarefootage;
cout << endl;
//Calculate the bill amount
billAmount = squarefootage * PER_SQUARE_FOOT;
cout << "Your free Business Customer Estimate for " << squarefootage << "square footage = " << billAmount;
}

C++ Airfare Charge Calculation project

I have to create a program to calculate charges for airfare. It's a simple program so far and I am not done adding to it, but every time I run it the result turns out to be 0. Is there something missing in my code? I am a beginner and I would appreciate any advice on improving my code. Thank you.
#include <iostream>
using namespace std;
void main () {
int distance = 0;
int num_bags= 0;
int num_meals= 0;
double distance_price = distance * 0.15;
double bag_price = num_bags * 25.00;
double meal_price = num_meals * 10.00;
double total_airfare = 0.00;
cout << "CorsairAir Fare Calculator" << endl;
cout << "Enter the distance being travelled: " << endl;
cin >> distance;
cout << "Enter number of bags checked: " <<endl;
cin >> num_bags;
cout << "Enter the number of meals ordered: " << endl;
cin >> num_meals;
total_airfare = (distance_price + bag_price + meal_price);
cout << total_airfare;
}
Your confusion is completely understandable - the piece you're missing is that when you assign a variable, you're assigning the left side to the result of the right side at that moment in time. It's not like algebra, where you say f(x) = x + 5 and f(x) is always whatever x + 5 is.
So, you assign double distance_price = distance * 0.15 when distance is 0 (which you just initialized). distance_price remains 0 even after you ask for input and change distance.
Do your price calculations after you ask for input, and everything will work just fine.
You are calculating the distance_price bag_price meal_price with default values i.e. 0 not with the value which you took from user.
Below code works fine and you won't see the issue.
#include <iostream>
using namespace std;
// My compiler did not allow void main so used int main
int main () {
int distance = 0;
int num_bags= 0;
int num_meals= 0;
double distance_price ;
double bag_price ;
double meal_price;
double total_airfare;
cout << "CorsairAir Fare Calculator" << endl;
cout << "Enter the distance being travelled: " << endl;
cin >> distance;
cout << "Enter number of bags checked: " <<endl;
cin >> num_bags;
cout << "Enter the number of meals ordered: " << endl;
cin >> num_meals;
distance_price = distance * 0.15;
bag_price = num_bags * 25.00;
meal_price = num_meals * 10.00;
total_airfare = 0.00;
total_airfare = distance_price + bag_price + meal_price;
cout << total_airfare;
return 0;
}
Result
CorsairAir Fare Calculator
Enter the distance being travelled:
200
Enter number of bags checked:
2
Enter the number of meals ordered:
2
100

Loop accepts first set of input and then reuses that value

I am currently learning C++ in school and one of our projects is to create a program to calculate a budget. When I run my program, the loop that accepts the input for item cost will take the input once and then reuse that value each time it loops back. I have already searched online for a solution and my teacher is just as confused about it as I am. It could be that there is a problem with Codeblocks but I have already tried it with a different editor. If anyone knows how I can fix it, that would be great.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
//Declares variables
float itemCount = 0;
float taxPercent = 0;
float itemCost = 0;
bool taxable = true;
float totalTaxable = 0;
float totalNontaxable = 0;
float total = 0;
//Receive user input
cout << "How many items to you have to buy: ";
cin >> itemCount;
cout << "\nWhat is the tax percentage (do not include the % sign): ";
cin >> taxPercent;
//This code runs once for every item
while (itemCount > 0){
//Receive the remaining user input
cout << "\nWhat is the cost of the item: ";
cin >> itemCost;
cout << "\nIs the item taxable (Please use either true or false): ";
cin >> taxable;
//Adds the item cost to either the taxable or nontaxable variables
if (taxable == true){
totalTaxable += itemCost;
cout << "true";
} else{
totalNontaxable += itemCost;
cout <<"false";
}
itemCount -= 1;
}
total = (totalTaxable * (1 + (taxPercent / 100))) + totalNontaxable;
cout << "\n--------------------------------------------------\n";
cout << "You must earn $";
cout << total;
cout << " to meet this budget\n\n";
}
As said in the comment, you can't use cin on boolean. From the doc :
The standard input stream is a source of characters determined by the environment.
So here's your fixed code (which will accept Y and nothing else) :
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
//Declares variables
float itemCount = 0;
float taxPercent = 0;
float itemCost = 0;
char taxable = '';
float totalTaxable = 0;
float totalNontaxable = 0;
float total = 0;
//Receive user input
cout << "How many items to you have to buy: ";
cin >> itemCount;
cout << "\nWhat is the tax percentage (do not include the % sign): ";
cin >> taxPercent;
//This code runs once for every item
while (itemCount > 0){
//Receive the remaining user input
cout << "\nWhat is the cost of the item: ";
cin >> itemCost;
cout << "\nIs the item taxable (Please use Y for Yes): ";
cin >> taxable;
//Adds the item cost to either the taxable or nontaxable variables
if (taxable == 'Y'){
totalTaxable += itemCost;
cout << "true";
} else{
totalNontaxable += itemCost;
cout <<"false";
}
itemCount -= 1;
}
total = (totalTaxable * (1 + (taxPercent / 100))) + totalNontaxable;
cout << "\n--------------------------------------------------\n";
cout << "You must earn $";
cout << total;
cout << " to meet this budget\n\n";
}

Nested loops to find max

I am coding a program to find the maximum of an equation over an interval given by the user. When I compile the code instead of outputting the maximum it gives me this
Please enter the first number of the interval to be checked:
Please enter the last number of the interval to be checked:
Please enter the desired initial step size:
sh: PAUSE: command not found
I figure the problem has to do with my loops, but I'm not sure how to rectify the situation.
Here's my code
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int a, b, delta, x, y;
int max = 0;
cout <<"Please enter the first number of the interval to be checked: " << endl;
cin >> a;
cout << "Please enter the last number of the interval to be checked: " << endl;
cin >> b;
cout << "Please enter the desired initial step size: " << endl;
cin >> delta;
for(x = a; x <= b; x = x+delta)
{
y = pow(x, 2)-7*x-18;
if (y > max)
{
max = y;
cout <<"The maximum over the interval from " << a <<" to " << b <<" is " << max;
}
else
{
delta= delta/2;
}
if (delta < pow( 10, -6))
{
break;
}
}
return 0;
}
Looking at your code it seems like that the value of delta should be in float as you are recursively dividing it by 2. Your pow (10,-2) doesn't do any useful comparison for that matter. even after everything it doesn't throw me that pause error. I ran it on VS 12 (C++11).

Counter not working?

I am writing a program for a homework assignment that calculates rental car rates based on make, days rented and miles driven. Overall the program works except, when the user is prompted for the number of cars to be calculated, the program continues to prompt the user for input after the number has been exceeded. Also, the formatting for the miles is correct for the first vehicle entered but changes for subsequent entries.
Any help with these two issues would be greatly appreciated!
Code:
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
// Change the console's background color.
system ("color F0");
// Declare the variables.
char carType;
string brand, f("Ford"), c("Chevrolet");
int counter = 0, cars = 0;
double days, miles, cost_Day, cost_Miles, day_Total;
cout << "Enter the number of cars you wish to enter: ";
cin >> cars;
cin.ignore();
while (counter <= cars)
{
cout << "Enter the car type (F or C): ";
cin >> carType;
cin.ignore();
cout << "Enter the number of days rented: ";
cin >> days;
cin.ignore();
cout << "Enter the number of miles driven: ";
cin >> miles;
cin.ignore();
if (carType == 'F' || carType == 'f')
{
cost_Day = days * 40;
cost_Miles = miles * .35;
day_Total = cost_Miles + cost_Day;
brand = f;
}
else
{
cost_Day = days * 35;
cost_Miles = miles * .29;
day_Total = cost_Miles + cost_Day;
brand = c;
}
cout << "\nCar Days Miles Cost\n";
cout << left << setw(12) << brand << right << setw(6) << days << right << setw(8) << miles
<< fixed << showpoint << setprecision (2) << setw(8) << right << "$" << day_Total << "\n\n";
counter++;
}
system ("pause");
}
You have started counting from 0 int counter = 0, cars = 0;
You then count until you are equal to the number that was entered (the "or equal to" bit of while (counter <= cars)).
As a worked example, if I want 3 entries:
Start: counter = 0, cars = 3.
0 <= 3: true
End of first iteration: counter = 1
1 <= 3: true
End of second iteration: counter = 2
2 <= 3: true
End of third iteration: counter = 3
3 <= 3: true (the "or equal" part of this)
End of FORTH iteration: counter = 4
4 <= 3: false -> Stop
We have completed 4 iterations instead of 3. If we only checked for "strictly less than" (counter < cars), the condition at the end of the third iteration would be false, and we'd have ended there.
The heading of your while loop should be:
while(counter < cars)
rather than
while(counter <= cars)