C++ Program to calculate Miles traveled and MPH - c++

Okay so I am new to C++ and I really don't understand what I am doing wrong in this program.
I need to have the user input the start and end mileage of a trip and the amount of hours it took. I then need to print the results in miles and kilometers.
My test variables are
start 1230
end 1240.5
hours .12
The results should be
Miles 10.5
mph 87.5
kilometers 16.9
kph 140.8
But that is not what I get.
// Lab 3 Exercise 2
// Calculate MPH (miles Per Hour) and KPH (Kilometers Per Hour).
//
// Program by: Mohamed El-Malah
#include <iostream>
#include <iomanip>
using namespace std;
int main ()
{
// Have the user enter his start and end mileage
double start_mileage, end_mileage;
cout << "Enter your starting mileage: ";
cin >> start_mileage;
cout << "Enter your end mileage: ";
cin >> end_mileage;
double trip_mileage = end_mileage - start_mileage;
// Have user input the hours the trip took
double total_hours, mph;
cout << "How man hours was the trip: ";
cin >> total_hours;
mph = trip_mileage / total_hours;
// Print the results in Miles and Kilometers
double trip_kilometers, kph;
trip_kilometers = trip_mileage * 1.6;
kph = trip_kilometers / total_hours;
cout << "Total miles " << setprecision(1) << setw(15) << trip_mileage << endl;
cout << " Miles/Hour " << setw(15) << mph << endl;
cout << "Total Kilometers" << setw(10) << trip_kilometers << endl;
cout << " Kilometers/Hour" << setw(10) << kph << endl;
}
Okay so I fixed the problem that I was computing the equations before I had the values.
However I still have a similar problem. My answers are not printed in single decimal points like I need them to be.
EX:
1e+001 instead of 10.5
9e+001 instead of 87.5

Corrected code:
// Lab 3 Exercise 2
// Calculate MPH (miles Per Hour) and KPH (Kilometers Per Hour).
//
// Program by: Mohamed El-Malah
#include <iostream>
#include <iomanip>
using namespace std;
int main ()
{
// Have the user enter his start and end mileage
double start_mileage, end_mileage;
cout << "Enter your starting mileage: ";
cin >> start_mileage;
cout << "Enter your end mileage: ";
cin >> end_mileage;
double trip_mileage = end_mileage - start_mileage;
// Have user input the hours the trip took
double total_hours, mph;
cout << "How man hours was the trip: ";
cin >> total_hours;
mph = trip_mileage / total_hours;
// Print the results in Miles and Kilometers
double trip_kilometers, kph;
trip_kilometers = trip_mileage * 1.6;
kph = trip_kilometers / total_hours;
/**** fixed stream manipulator makes cout not use scientific notation ****/
cout << "Total miles " << fixed << setprecision(1) << setw(15) << trip_mileage << endl;
cout << " Miles/Hour " << setw(15) << mph << endl;
cout << "Total Kilometers" << setw(10) << trip_kilometers << endl;
cout << " Kilometers/Hour" << setw(10) << kph << endl;
}
You had messed with the ordering of variables total_hours and trip_mileage. Make sure you use/calculate the value of the variables after you have taken relevant input from the user, otherwise random values will be used.
Additionally, to make cout not use scientific notation, you must use std::fixed stream manipulator.

See here:
double trip_mileage = end_mileage - start_mileage;
cout << "Enter your starting mileage: ";
cin >> start_mileage;
cout << "Enter your end mileage: ";
cin >> end_mileage;
You're computing your trip mileage before you asked your user for the necessary inputs. Declare the variable but don't do the computation until later:
double trip_mileage;
cout << "Enter your starting mileage: ";
cin >> start_mileage;
cout << "Enter your end mileage: ";
cin >> end_mileage;
trip_mileage = end_mileage - start_mileage;
You make the some mistake again with total_hours. I'll let you figure that one out.

Change order of these lines. Because earlier you are computing mph even before you had input of total_hours. In that case total_hours is assigned a garbage value and your results differ.
double total_hours, mph;
cout << "How man hours was the trip: ";
cin >> total_hours;
mph = trip_mileage / total_hours;
and same about trip_mileage
cout << "Enter your starting mileage: ";
cin >> start_mileage;
cout << "Enter your end mileage: ";
cin >> end_mileage;
double trip_mileage = end_mileage - start_mileage;

Related

Using getline(cin.input) to input a string in a while loop

Currently working on the following homework problem:
Enter destination city, miles traveled to get there and gallons of gasoline used for any number of trips entered at the keyboard (use ctl+z to stop). Use a function to compute miles per gallon(miles traveled/gallons used). Display the destination city and miles per gallon for each trip entered. Sum the miles traveled and give a count of the number of trips made. Display these at the end of the program.
The problem occurs during the second iteration of the while loop.
When asking the using for input, the output "Enter destination city, ctrl+z to stop:" and 'Enter miles to destination and gallons of gasoline needed, ctrl+z to stop:" are merged into one output.
In other words, the console does not allow the user time to input a city after asking for a destination the second time. Instead, both outputs are displayed back to back and whatever is input is stored into gallons and gasoline resulting in an error.
I have tried adding more likes between the code.
I tried adding a system("pause") between the lines.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
float mpgFunc(float, float);
int main()
{
//variable declaration
string destination;
float milesToDest, gasolineNeeded, MPG, totalMiles = 0.0f;
int count = 0;
//input phase
cout << "Enter destination city, ctrl+z to stop: " << endl;
getline(cin, destination);
cout << "Enter miles to destination and gallons of gasoline needed,
ctrl+z to stop: " << endl;
cin >> milesToDest >> gasolineNeeded;
while (!cin.eof())
{
MPG = mpgFunc(milesToDest, gasolineNeeded); //function call
count = count + 1; //counter
totalMiles = totalMiles + milesToDest; //sum
cout << setprecision(2) << fixed;
cout << "Destination city: " << setw(10) << destination <<
endl;
cout << "Miles per gallon: " << setw(10) << MPG << endl;
/* Problem
cout << "Enter destination city, ctrl+z to stop: " << endl <<
endl;
getline(cin, destination);
cout << "Enter miles to destination and gallons of gasoline
needed, ctrl+z to stop: " << endl;
cin >> milesToDest >> gasolineNeeded;
problem happens here the two outputs are merged into one output */
}
cout << endl;
cout << "Total miles traveled: " << setw(8) << totalMiles << endl;
cout << "Total trips taken: " << setw(8) << count << endl;
system("pause");
return 0;
}//end main
float mpgFunc(float milesToDest, float gasolineNeeded)
{
float MPG;
MPG = milesToDest / gasolineNeeded;
return MPG;
}

Having some trouble with a assignment in c++

I have a assignment I've been working on and my code is working but the results are off by a hair. I know the issue has to do with rounding but I just can't seem to figure out where the issue lies. I've included the assignment details as well as the results i'm getting versus the expected result. Any help is appreciated.
Link for images https://imgur.com/a/bqIcxfT
'''
// This program will display the size of a population for given number of years
// taking into account annual birth and death rates as well as the number of
// people who move away and move into the area.
#include <iostream>
#include <iomanip>
using namespace std;
//Function prototype
double calculatePop (double, double, double, int, int);
int main ()
{
double P; // Starting population
double B; // Annual birth rate
double D; // Annual death rate
int A; // Average number of people who arrive
int M; // Average number of people who move away
int nYears; // The number of years to display
cout << "This program calculates population change." << endl;
// Set numeric formatting
cout << setprecision(0) << fixed;
// Get starting population size
cout << "Enter the starting population size: ";
cin >> P;
while (P<2){
cout << "Starting population must be 2 or more.";
cout << "Please re-enter:";
cin >> P;}
// Get the annual birth rate
cout << "Enter the annual birth rate (as % of current population): ";
cin >> B;
while (B<0){
cout << "Birth rate percent cannot be negative.";
cout << "Please re-enter:";
cin >> B;}
B/=100;
// Get annual death rate
cout << "Enter the annual death rate (as % of current population): ";
cin >> D;
while (D<0){
cout << "Death rate percent cannot be negative.";
cout << "Please re-enter:";
cin >> D;}
D/=100;
// Get number of people who arrive
cout << "How many individuals move into the area each year? ";
cin >> A;
while (A<0){
cout << "Arrivals cannot be negative.";
cout << "Please re-enter:";
cin >> A;}
// Get number of people who move away
cout << "How many individuals leave the area each year? ";
cin >> M;
while (M<0){
cout << "Departures cannot be negative.";
cout << "Please re-enter:";
cin >> M;}
// Get number of years to see data for
cout << "For how many years do you wish to view population changes? " << endl << endl;
cin >> nYears;
while (nYears<1){
cout << "Years must be one or more.";
cout << "Please re-enter:";
cin >> nYears;}
cout << "Starting population: " << P << endl << endl;
//Display the population to user
for (int y=1; y<=nYears; y++)
{
P = calculatePop(P, B, D, A, M);
cout << "Population at the end of year " << y << " is " << P << ".\n";
}
}
double calculatePop (double P, double B, double D, int A, int M)
{
double N; //New Population Size
N = P + (B*P) - (D*P) + A - M;
return N;
}
'''
The value is correctly calculated but not outputted the same way as in the assignment. Setting setprecision(0) along with fixed will round the number to the nearest integer while the result shown in the assignment is the truncated number. To truncate the result, use
cout << "Population at the end of year " << y << " is " << int(P) << ".\n";

Calculating Interest Rate

So I am trying to learn C++ for a college course and I have to write a program which uses this formula:
Amount = Principal * (1 + Rate/T)^T
Where principal is the balance in savings, rate is the interest rate, and t is the number of times the interest is compounded during a year. According to the book if you type in 4.25 as the interest rate and 12 as the number of times compounded with the principal as 1000.00 then you should get 43.34 as interest and the total amount should be 1043.34. I'm not sure if I am coding it wrong or what but I was wondering if anyone could help me out with any mistakes I might have done! I'm trying to do it on my own for about a day or two now but I have had no luck.
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
double PRINCIPAL;
double INTEREST_RATE;
double COMPOUND_AMOUNT;
cout << "What is your savings account balance?: " << endl;
cin >> PRINCIPAL;
cout << "What is your annual interest rate?: " << endl;
cin >> INTEREST_RATE;
cout << "How many times has your interest been compounded?: " << endl;
cin >> COMPOUND_AMOUNT;
double amt1 = 1 + (INTEREST_RATE/COMPOUND_AMOUNT);
double AMOUNT = PRINCIPAL * pow(amt1, COMPOUND_AMOUNT);
cout << "Interest Rate: " << INTEREST_RATE << endl;
cout << "Times Compounded: " << COMPOUND_AMOUNT << endl;
cout << "Principal: " << PRINCIPAL << endl;
cout << "Interest: " << INTEREST_RATE * COMPOUND_AMOUNT << endl;
cout << "Amount: " << AMOUNT << endl;
system("pause");
return 0;
}
This is a math error. If you're going to take in interest rates as '4.25' %, you need to divide the interest rate by 100. The code below gave me the amount as 1043.34 when 4.25 is entered as the interest rate.
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
double PRINCIPAL;
double INTEREST_RATE;
double COMPOUND_AMOUNT;
cout << "What is your savings account balance?: " << endl;
cin >> PRINCIPAL;
cout << "What is your annual interest rate? (in %): " << endl;
cin >> INTEREST_RATE;
INTEREST_RATE /= 100;
cout << "How many times has your interest been compounded?: " << endl;
cin >> COMPOUND_AMOUNT;
double amt1 = 1 + (INTEREST_RATE/COMPOUND_AMOUNT);
double AMOUNT = PRINCIPAL * pow(amt1, COMPOUND_AMOUNT);
cout << "Interest Rate (%): " << INTEREST_RATE * 100 << endl;
cout << "Times Compounded: " << COMPOUND_AMOUNT << endl;
cout << "Principal ($): " << PRINCIPAL << endl;
cout << "Interest ($): " << AMOUNT - PRINCIPAL << endl;
cout << "Amount ($): " << AMOUNT << endl;
system("pause");
return 0;
}
for interest your book is talking about the amount of interest in dollars, i.e. AMOUNT - PRINCIPAL.

C++ Segfault No compile errors can't find cause

Hoping someone can help. I'm able to compile with no error, I'm not finding any syntax errors but when I run this, it crashes. Debug segfaults on launch. Full disclosure, this is homework. I'm not asking for someone to code this, just look at my problem and my existing code and maybe point me toward what I did that broke this so badly?
Question: You found an exciting summer job for five weeks. It pays, say, $15.50 per hour. Suppose that the total tax you pay on your summer job income is 14%. After paying the taxes you spend 10 % of your net income to buy new clothes and other accessories for the next school year and 1% to buy school supplies. After buying clothes and school supplies, you use 25% of the remaining money to buy savings bonds. For each dollar you spend to buy savings bonds, your parents spend $0.50 to buy additional savings bonds for you. Write a program that prompts the user to enter the pay rate for an hour and the number of hours you worked each week. The program then outputs the following:
a. Your income before and after taxes from your summer job.
b. The money you spend on clothes and other accessories.
c. The money you spend on school supplies.
d. The money you spend to buy savings bonds.
e. The money your parents spend to buy additional savings bonds for you.
Code:
// Libraries defined
#include <iomanip>
#include <iostream>
using namespace std;
//Main function
int main ()
{
//Input variables
double hourlyrate;
double hweek1;
double hweek2;
double hweek3;
double hweek4;
double hweek5;
//Output variables
double beforetax;
double netincome;
double clothmoney;
double suppliesmoney;
double moneyonbonds;
double additionalbonds;
double remain;
//This statement takes care of the decimal places
cout << fixed << showpoint << setprecision(2);
//Input from user
cout << "Enter your hourly rate: " << hourlyrate;
cin >> hourlyrate;
cout << "Week 1: " << hweek1;
cin >> hweek1;
cout << "Week 2: " << hweek2;
cin >> hweek2;
cout << "Week 3: " << hweek3;
cin >> hweek3;
cout << "Week 4: " << hweek4;
cin >> hweek4;
cout << "Week 5: " << hweek5;
cin >> hweek5;
//Mathematics
beforetax = hourlyrate * (hweek1 + hweek2 + hweek3 + hweek4+
hweek5) ;
netincome = beforetax - beforetax * 0.14;
clothmoney = netincome * 0.1;
suppliesmoney = netincome * 0.01;
remain = netincome - clothmoney - suppliesmoney;
moneyonbonds = remain * 0.25;
additionalbonds = static_cast<double>(moneyonbonds) * .50;
//Output to user
cout << endl << "Income before tax = $" << beforetax << endl
<< "Net income = $" << netincome << endl << "Money for clothes/accesories = $"
<< clothmoney << endl << "Money for supplies = $"<< suppliesmoney << endl
<< "Money for saving bonds = $" << moneyonbonds << endl
<< "Additional saving bonds money = $" << additionalbonds;
return 0;
}
I received this error
cout << "Enter your hourly rate: " << hourlyrate;
You try to output the variable before you initialize it.
This is probably unintentional.
The next line is
cin >> hourlyrate
It is the same for every variable. You should initialize them or not output them.
Are you sure about this:
cout << "Enter your hourly rate: " << hourlyrate;
cin >> hourlyrate;
cout << "Week 1: " << hweek1;
cin >> hweek1;
cout << "Week 2: " << hweek2;
cin >> hweek2;
cout << "Week 3: " << hweek3;
cin >> hweek3;
cout << "Week 4: " << hweek4;
cin >> hweek4;
cout << "Week 5: " << hweek5;
cin >> hweek5;
I think that you wanted:
cout << "Enter your hourly rate: ";
cin >> hourlyrate;
instead of:
cout << "Enter your hourly rate: "<< hourlyrate;
cin >> hourlyrate;

C++ Program not reading formulas

My program I have been working on is supposed to output the following:
* The number of gallons of paint required
* The hours of labor required
* The cost of the paint
* The labor charges
* The total cost of the paint job
However, it displays 0 in every field.. What have I done wrong now?
Your help would be greatly appreciated.
Here is my code:
//Headers
#include <iostream>
#include <fstream>
#include <cmath>
#include <cstdlib>
#include <iomanip>
using namespace std;
void PaintJobEstimator(double gallonprice, double calc)
{
float numBucket=0;
float hours=0;
float bucketCost=0;
float laborCharges=0;
float totalCost=0;
//calculates number of buckets of paint (gallons) needed
numBucket=numBucket+calc*(1/115);
//calculates paint cost
bucketCost=bucketCost+gallonprice*numBucket;
//calculates labor hour
hours=hours+calc*(8/115);
//calculates labor charges
laborCharges=hours*18;
//calculates total cost
totalCost=totalCost+bucketCost+laborCharges;
//Console output
cout << "The number of Gallons of paint required:\t" << setprecision(2) << numBucket << endl;
cout << "The hours of labor required:\t" << setprecision(2) << hours << " hrs" << endl;
cout << "The labor charges:\t$" << setprecision(2) << laborCharges << endl;
cout << "The cost of the paint:\t$" << setprecision(2) << bucketCost << endl;
cout << "The total cost of the paint job:\t$" << setprecision(2) << totalCost << endl;
}
void main ()
{
int rooms;
double calc=0;
double wallspace;
double gallonprice;
cout << "=========================================================\n";
cout << "___________________Paint Job Estimator___________________\n";
cout << "_________________________________________________________\n";
cout << endl;
cout << "Enter the number of rooms: ";
cin >> rooms;
while (rooms<1) //validates rooms
{
cout << "Invalid entry, enter one or more rooms:\t";
cin >> rooms;
}
for (int roomNum=1;
roomNum<=rooms;
roomNum++)
{
cout << "Enter the wall space in square meters for room " << roomNum << ":\t" << endl;
cin >> wallspace;
while (wallspace < 0.01)//validates wallspace
{
cout << "Invalid entry, please re-enter the wall area for room " << roomNum << ":\t";
cin >> wallspace;
}
calc=calc+wallspace;
}//end loop
cout << "\nEnter price of the paint per gallon: ";
cin >> gallonprice;
if (gallonprice <10) //validates price per gallon
{
cout << "Invalid entry, Reenter price at a $10.00 minimum: ";
cin >> gallonprice;
}
PaintJobEstimator(gallonprice,wallspace);
system ("pause");
}
Here is a screenshot of the console:
You're multiplying by zero in some of the calculations. For example, in the following line of code:
numBucket=numBucket+calc*(1/115);
You put 1/115 in parenthesis, which evaluates to zero because of integer division. To achieve the desired effect, try:
numBucket = calc / 115.0f;