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;
}
Related
I'm trying to complete an assignment but I'm having difficulty with the math expressions and variables in general. I'm trying to make a program that takes user info on groceries and then outputs a receipt. Here is my code.
#include <iostream>
#include <string>
using namespace std;
int main()
{
//user input
string firstItem, secondItem;
float firstPrice, secondPrice;
int firstCount, secondCount;
double salesTax = 0.08675;
double firstExt = firstPrice * firstCount;
double secondExt = secondPrice * secondCount;
double subTotal = firstExt + secondExt;
double tax = subTotal * salesTax;
double total = tax + subTotal;
//user input
cout << "What is the first item you are buying?" << endl;
getline(cin, firstItem);
cout << "What is the price of the " << firstItem << "?" << endl;
cin >> firstPrice;
cout << "How many " << firstItem << "s?" <<endl;
cin >> firstCount;
cin.ignore();
cout << "What is the second item you are buying?" << endl;
getline(cin, secondItem);
cout << "what is the price of the " << secondItem << "?" << endl;
cin >> secondPrice;
cout << "How many " << secondItem << "s?" << endl;
cin >> secondCount;
// receipt output
cout << "1st extended price: " << firstExt << endl;
cout << "2nd extended price: " << secondExt << endl;
cout << "subtotal: " << subTotal << endl;
cout << "tax: " << tax << endl;
cout << "total: " << total << endl;
return 0;
}
The program output either 0 for all or negatives.
Your calculations must go after you read in the values, not before. You're making your calculations based on uninitialized variables.
A declaration and initialisation like
double firstExt = firstPrice * firstCount;
initialises firstExt to be the product of the current values AT THAT POINT of firstPrice and firstCount.
It doesn't set up some magic so that the value of firstExt is recalculated whenever the values of firstPrice or firstCount are changed.
In your case, firstPrice and firstCount are uninitialised variables when you do this. Accessing values of uninitialised variables of type int gives undefined behaviour.
What you need to do is something like
cout << "What is the price of the " << firstItem << "?" << endl;
cin >> firstPrice;
cout << "How many " << firstItem << "s?" <<endl;
cin >> firstCount;
firstExt = firstPrice*firstCount; // do the calculation here
If the value of firstExt is not needed until this point, you can declare it here instead;
double firstExt = firstPrice*firstCount; // do the calculation here
which means any earlier use of firstExt will give a compiler diagnostic.
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;
I need help with a program for school. We had to write a program that asks the user for information about a baseball player. We need to calculate the players batting average with their games played, number of times at bat and number of hits. I am running into an issue where my computation for the average is outputting a set number and not performing any computations. I am entering whole integers for all the variables that are used for calculation. So i would input numbers like 1, 4 , 10 etc... As the program stands the value my formula is setting itself equal to is 15903.876. All of my variables used for the average formula are declared as integers and the batting average itself is declared as a double. I have done some debugging my self and found that the computation messes up when it divides the number of times at bat by the number of hits. If anyone could help me figure out the issue i would appreciate it.
//libaries
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
using namespace std;
class battingAverage
{
public:
string pName;
int nBats;
int tHits;
int gPlayed;
int gcalled;
double average;
double average1;
double playeraverage;
};
int main()
{
string numberPlayers;
int nplayers;
//enters the number of players the user wants to enter data for
cout << "Enter the number of players you want to enter data for: ";
cin >> numberPlayers;
cout << endl;
//converts the value of numberPlayers to nplayers
istringstream convert(numberPlayers);
//sets integer nplayers equal to the value of the string numberPlayers
if(! (istringstream(numberPlayers) >> nplayers) )
{
nplayers = 0;
}
cout << "This program calculates the batting average of baseball players.\nYou may enter data for " << nplayers << " players." << endl;
battingAverage ba[nplayers];
int index = 0;
//while statement to get data
while(index < nplayers)
{
cout << "Enter the players last name: " << endl;
cin >> ba[index].pName;
cout << "Enter the number of games the player played: " << endl;
cin >> ba[index].gPlayed;
cout << ba[index].gPlayed << endl;
cout << "Enter the number of games the player was called in for: " << endl;
cin >> ba[index].gcalled;
cout << ba[index].gcalled << endl;
cout << "Enter the number of times the player was at bat: " << endl;
cin >> ba[index].nBats;
cout << ba[index].nBats << endl;
cout << "Enter the number of time the player hit: " << endl;
cin >> ba[index].tHits;
cout << ba[index].tHits << endl;
if(ba[index].tHits > ba[index].nBats)
{
cout << "Enter a valid value for the number of times the player hit: ";
cin >> ba[index].tHits;
}
cout << endl;
index++;
}
//rounds average to 3 decimal places
cout << fixed << setprecision( 3 );
//average formula
ba[index].playeraverage = (ba[index].nBats / ba[index].tHits) * (ba[index].gPlayed / ba[index].gcalled);//error
cout << ba[index].playeraverage << endl << endl;//just temp line to check calculation of average.
ba[index].average = .000;
ba[index].average1 = .099;
while(ba[index].average < 1 && ba[index].average1 < .899)
{
ba[index].average +=.100;
ba[index].average1 += .1;
//prints chart
cout << setprecision( 1 ) << ba[index].average << "00" << setprecision( 3 ) << setw(12) << ba[index].average1 << endl;
}
cout << "1.000" << setw(12) << "1.000" << endl;
//version of system pause
cout << "\nPress enter to continue...";
cin.sync();
cin.ignore();
return 0;
}
On this line:
ba[index].playeraverage = (ba[index].nBats / ba[index].tHits) * (ba[index].gPlayed / ba[index].gcalled);//error
You have this expression:
(ba[index].nBats / ba[index].tHits)
Because both nBats and tHits are integers, you're using only integer math.
The answer will be an integer.
For example:
nBats = 10 & tHits = 3, you'd expect the expression to be 3.333.
But it would only be 3
To fix this, I recommend changing to:
((double)ba[index].nBats / ba[index].tHits)
Same thing again with the expression about gPlayed and gcalled.
Your value of index is wrong during the calculations.
I found this as soon as I put your code in a debugger and stepped through it, something you really should have done yourself.
You start with int index = 0;, and increment it as the user puts in each player's data.
At the end of the input-loop, index is now the same as the number of players.
(eg. if you had 5 players, index is now 5, and the player data is stored in ba[0], ba[1], ba[2], ba[3], and ba[4])
Note that at this point ba[5] is NOT valid data. But that is exactly where ba[index] is!
You do all your calculations on ba[index], which is invalid data, and you wonder why you get meaningless results?
I recommend you set index back to 0 before starting your calculations, and make another loop that does the necessary calculations for each player 0...4.
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;
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Is there a built-in function that comma-separates a number in C, C++, or JavaScript?
How do you set the cout locale to insert commas as thousands separators?
How I could input "commas(,)" to my outputs. for example: $16982 but I need it to look like: $16,982.
Here is my code so far:
#include <iostream> // I/O Stream for form
using namespace std; // to prevent redundance of std
int main() // main to form as integer; begins form
{
double housing, food, clothing, transportation, education, healthcare, vacations; // Declaring variables for code below as doubles so you can hold a bigger number; decimal values
// List of expense options that you can choose from
cout << " ----------Yearly Expenses----------" << endl; // outputs heading to user "yearly expenses"
cout << " " << endl; // ends the line and centers the code
cout << " housing $" ; // outputs housing to show user what expenses they can choose from
cout << " " << endl; // ends the line and centers the code
cout << " education $" ; // outputs education to show user what expenses they can choose from
cout << " " << endl; // ends the line and centers the code
cout << " food $" ; // outputs food to show user what expenses they can choose from
cout << " " << endl; // ends the line and centers the code
cout << " clothing $" ; // outputs clothing to show user what expenses they can choose from
cout << " " << endl; // ends the line and centers the code
cout << " transportation $" ; // outputs transportation to show user what expenses they can choose from
cout << " " << endl; // ends the line and centers the code
cout << " healthcare $" ; // outputs healthcare to show user what expenses they can choose from
cout << " " << endl; // ends the line and centers the code
cout << " vacations $" ; // outputs vacations to show user what expenses they can choose from
cout << " " << endl; // ends the line and centers the code
cout << "\n\n *****Enter your expenses*****" << endl; // outputs heading to user "enter your expenses"
cout << "\n housing: $"; // outputs to user "heading"
cin >> housing; //
cout << "\n education: $"; // outputs to user "education"
cin >> education;
cout << "\n food: $"; // outputs to user "food"
cin >> food;
cout << "\n clothing: $"; // outputs to user "clothing"
cin >> clothing;
cout << "\n transportation: $"; // outputs to user "transportation"
cin >> transportation;
cout << "\n healthcare: $"; // outputs to user "healthcare"
cin >> healthcare;
cout << "\n vacations: $"; // outputs to user "vacations"
cin >> vacations;
double total; // Declaring variable to hold all of the expenses variables
total = (housing + education + food + clothing + transportation + healthcare + vacations); // shows "total" equals all expenses variables added together
cout << "\n\n <><><><>total with 23% tax<><><><>" << endl << endl; // Outputs the heading "total with 23% tax" to user
total = (total * .23) + total; // total equals total multiplied by the 23% to get the percentage tax on your expense
cout << " $" << total << endl; // outputs the total to the user with the added 23% tax
system("pause>nul");
return 0; // returns nothing/0
}
Well you could try converting your int into a string then format it the way you want...Anyway you just cant insert commas into a int type directly.