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)
Related
Need to take out the highest and lowest numbers of 5 judges 0 to 10 on the score
cout << "Please enter the name of the athelete.\n";
getline(cin, name);
cin >> name;
cout << "Please enter the first judge's score below\n";
cout << "Please enter a score between 0 and 10.\n";
cin >> First_Score;
Pseudo code
loop for 5 answers
sort them
sum of middle 3
avg sum / 3
print
The simplest solution would be to create two additional variables. The first, 'lowest', to store the lowest value and the second, 'biggest' to store the biggest value.
int lowest = 0, biggest = 11;
...
cin >> First_Score;
while (First_Score < 0 || First_Score > 10)
{
cout << "That is not a valid input, please pick between 0 and 10.\n";
cin >> First_Score;
cout << "Your selection was " << First_Score << endl;
}
lowest = First_Score;
biggest = First_Score;
...
And then for each judge :
cout << "Please enter the fifth judge's score here below\n";
cin >> Fifth_Score;
while (Fifth_Score < 0 || Fifth_Score > 10)
{
cout << "That is not a valid input, please pick between 0 and 10.\n";
cin >> Fifth_Score;
cout << "Your selection was " << Fifth_Score << endl;
}
if(lowest > Fifth_Score)
lowest = Fifth_Score;
if(biggest < Fifth_Score)
biggest = Fifth_Score;
...
int sum = Avg_Score = (First_Score + Second_Score + Third_Score + Fourth_Score + Fifth_Score);
Avg_Score = (sum - lowest - biggest) / 3;
...
Always separate input and logic.
#include <vector> // std::vector
#include <numeric> // std::sort, std::accumulate
#include <cassert> // assert
auto score(std::vector<double> scores) {
assert(scores.size()>2);
auto n = scores.size() - 2;
// sort ...
// sum ...
return sum / n;
}
int main() {
assert(score({1,5,9}) == 5);
assert(score({5,5,5}) == 5);
assert(score({0,5,0}) == 0);
assert(score({1,2,3,4,5,6}) == 3);
}
I left the actual implementation for you. My implementation fits in three lines.
I hope this inspires you to get a clean implemntation, that you can easily use to write the rest of the program with.
When I run the program with either one or more customers. It seems to be that Only with the first customer data, the code I have does not do the calculations correctly for the first customer when trying to get the monthly payments and interest but the calculations are done correctly for the rest of the customers data inputted. What am I missing? Thank you.
#include <iostream>
#include <string>
#include <cmath>
#include <iomanip>
#include <vector>
using namespace std;
int main()
{
//Variables
vector <double> Loanlgth, Loanamt, interestRate;
vector <double> monthlyPay(100), loanTotal(100), creditScore(100), totalInterest;
char yes;
const int INPUT_CUSTOMER = 1, DISPLAY_LOAN = 2, EXIT_PROGRAM = 3;
vector <string> customerName;
int option;
int numCustomers = 0;
int index = 0;
//Program
cout << "Thank you for choosing The Bank of UA for your loan requirements!\n\n";
do
{
cout << "UA Bank menu:\n\n"
<< "1. Enter your information\n"
<< "2. See your loan requirements\n"
<< "3. Exit program\n\n"
<< "Choose an option: ";
cin >> option;
while (option < INPUT_CUSTOMER || option > EXIT_PROGRAM)
{
cout << "Please enter a valid menu option: ";
cin >> option;
}
if (option == 1) //Customer enters their information
{
cout << "Please enter the number of customers you would like\n"
<< " to enter loan information for: ";
cin >> numCustomers;
for (index = 0; index < numCustomers; index++)
{
string tempName;
double tempLoanamt, tempLoanlgth, tempcreditScore, tempinterestRate, tempinterest;
cout << "Please enter your name: ";
cin >> tempName;
customerName.push_back(tempName);
cout << "Please enter the loan amount: $";
cin >> tempLoanamt;
Loanamt.push_back(tempLoanamt);
cout << "Please enter the length of the loan in months: ";
cin >> tempLoanlgth;
Loanlgth.push_back(tempLoanlgth);
cout << "What is your current credit score? ";
cin >> tempcreditScore;
creditScore.push_back(tempcreditScore);
if (tempcreditScore <= 600)
tempinterestRate = .12;
interestRate.push_back(tempinterestRate);
if (tempcreditScore > 600)
tempinterestRate = .05;
interestRate.push_back(tempinterestRate);
//Calculations
tempinterest = Loanamt[index] * interestRate[index];
totalInterest.push_back(tempinterest);
loanTotal[index] = (Loanamt[index] + totalInterest[index]);
monthlyPay[index] = loanTotal[index] / Loanlgth[index];
}
}
if (option == 2) // Displays monthly payment
{
cout << fixed << setprecision(2);
for (index = 0; index < numCustomers; index++)
cout << customerName[index] << " your total loan is " << loanTotal[index] << "\n"
<< "with a monthly payment of $" << monthlyPay[index] << "\n"
<< "for " << Loanlgth[index] << " months with an interest\n"
<< "rate of " << interestRate[index] << endl;
}
} while (option != EXIT_PROGRAM);
system("pause");
return 0;
}
Currently, interestRate is populated wrongly. Initially, it contains a garbage value because it is not initialized and if the first condition is not true, the garbage value is pushed, otherwise .12. Next, if the second condition is true, .05 is pushed, otherwise the values from the above flow. So, these combinations of garbage and assigned values are causing values to be pushed twice.
Here's your code:
if (tempcreditScore <= 600)
tempinterestRate = .12;
interestRate.push_back(tempinterestRate);
if (tempcreditScore > 600)
tempinterestRate = .05;
interestRate.push_back(tempinterestRate);
You can correct this in a number of ways:
// push after the calculation is complete
if (tempcreditScore <= 600)
tempinterestRate = .12;
if (tempcreditScore > 600)
tempinterestRate = .05;
interestRate.push_back(tempinterestRate);
or, with if-else (preferable):
if (tempcreditScore <= 600)
tempinterestRate = .12;
else
tempinterestRate = .05;
interestRate.push_back(tempinterestRate);
or, with ternary operator ?: (conciseness and you can make it const):
const double tempinterestRate = (tempcreditScore <= 600 ? .12 : .05);
interestRate.push_back(tempinterestRate);
Apart from this, there are a number of points:
The naming convention is inconsistent throughout the code.
The variables must be initialized because the uninitialized ones may lead to Undefined Behavior.
In the absence of an aggregate type such as struct or class and with multiple pieces of information to store separately in vectors, it is better to keep all the push_backs exactly to once per iteration.
Magic numbers can be avoided for 600, .12 and .5.
The magic numbers for option comparison in if conditions can be removed with their proper constant equivalents i.e. INPUT_CUSTOMER and DISPLAY_LOAN. And, if-else can be used instead of if-if.
The scoping could be improved by moving the variables and objects closer to where they are used.
The vertical blank spaces can improve readability for relevant code blocks.
And, Why is "using namespace std;" considered bad practice?
There might be some other points that you can observe in the following updated code (live):
#include <iostream>
#include <string>
#include <iomanip>
#include <vector>
int main()
{
// Variables
std::vector<std::string> customerNames;
std::vector<double> loanLengths, loanAmounts, interestRates;
std::vector<double> monthlyPays, loanTotals, creditScores, totalInterests;
// Program
std::cout << "Thank you for choosing The Bank of UA for your loan requirements!\n\n";
const int INPUT_CUSTOMER = 1, DISPLAY_LOAN = 2, EXIT_PROGRAM = 3;
int option = EXIT_PROGRAM;
do
{
std::cout << "UA Bank menu:\n\n"
<< "1. Enter your information\n"
<< "2. See your loan requirements\n"
<< "3. Exit program\n\n"
<< "Choose an option: ";
std::cin >> option;
while (option < INPUT_CUSTOMER || option > EXIT_PROGRAM)
{
std::cout << "Please enter a valid menu option: ";
std::cin >> option;
}
if (option == INPUT_CUSTOMER) //Customer enters their information
{
int numCustomers = 0;
std::cout << "Please enter the number of customers you would like\n"
<< " to enter loan information for: ";
std::cin >> numCustomers;
for ( int index = 0; index < numCustomers; index++ )
{
std::string name;
double loanAmount = 0.0, loanLength = 0.0, creditScore = 0.0;
std::cout << "Please enter your name: ";
std::cin >> name;
customerNames.push_back( name );
std::cout << "Please enter the loan amount: $";
std::cin >> loanAmount;
loanAmounts.push_back( loanAmount );
std::cout << "Please enter the length of the loan in months: ";
std::cin >> loanLength;
loanLengths.push_back( loanLength );
std::cout << "What is your current credit score? ";
std::cin >> creditScore;
creditScores.push_back( creditScore );
double interestRate = 0.0;
if (creditScore <= 600)
interestRate = .12;
else
interestRate = .05;
// Ternary operator (?:) may also be used here
// const double interestRate = creditScore <= 600 ? .12 : .05;
interestRates.push_back(interestRate);
//Calculations
const double tempTotalInterest = loanAmounts[index] * interestRates[index];
totalInterests.push_back( tempTotalInterest );
const double tempTotalLoan = loanAmounts[index] + totalInterests[index];
loanTotals.push_back( tempTotalLoan );
const double tempMonthlyPay = loanTotals[index] / loanLengths[index];
monthlyPays.push_back( tempMonthlyPay );
}
}
else if (option == DISPLAY_LOAN) // Displays monthly payment
{
std::cout << std::fixed << std::setprecision(2);
for (int index = 0; index < customerNames.size(); index++)
{
std::cout << "\n---\n";
std::cout << customerNames[index] << " your total loan is " << loanTotals[index]
<< "\nwith a monthly payment of $" << monthlyPays[index]
<< "\nfor " << loanLengths[index] << " months with an interest"
<< "\nrate of " << interestRates[index] << std::endl;
std::cout << "---\n";
}
}
} while (option != EXIT_PROGRAM);
return 0;
}
This program will need to handle all grades for 10 students.
Each student has a first and last name, an id number,
3 homework grades, 3 labs grades, 3 test grades, and 1 final exam grade.
display the final course grade in both numbered and letter version
The equation only works for the first set of grades then it adds a little bit to the next average I just can't figure out whats wrong.
/*This program will need to handle all grades for 10 students.
Each student has a first and last name, an id number,
3 homework grades, 3 labs grades, 3 test grades, and 1 final exam grade.
display the final course grade in both numbered and letter version
*/
#include <iostream> // main library
#include <string> //enables use of strings
#include <iomanip> // for setw
#include <Windows.h> // used to set console title
using namespace std; // for cout and cin
const int MAXSTUDENTS = 2;
const int MAXGRADES = 3;
const int MINGRADES = 1;
int main()
{// Get names form students
SetConsoleTitle("Gradebook");
double hwGrade[MAXSTUDENTS][MAXGRADES];
double labGrade[MAXSTUDENTS][MAXGRADES];
double testGrade[MAXSTUDENTS][MAXGRADES];
double feGrade[MAXSTUDENTS];
double final_num_grade[MAXSTUDENTS];
double hwAve =0, labAve=0, testAve=0; // this will be used to calculate the averages
string fName[MAXSTUDENTS];
string lName[MAXSTUDENTS];
string line; // to set the two string variables
string id[MAXSTUDENTS]; // id will be a whole number so int was apropiate
//first for statement. ensuere that the program is run 10 times
for (int s = 0; s < MAXSTUDENTS; s++) {
cout << "Enter student's first name: "; // ask the user for the first name
getline(cin, fName[s]); // accepts students first name
cout << "Enter stedent's last name: "; //ask the user for last name
getline(cin, lName[s]); // accepts students last name
cout << "Enter student's id: "; // ask user for student id
getline(cin, id[s]);
// this loop will ask for three homework grades
for (int n = 0; n < MAXGRADES; n++) {
cout << "Homework grade " << n + 1 << " is "; //tells the user waht the program needs
cin >> hwGrade[s][n]; //lets the user input the homework grades
hwAve += hwGrade[s][n];
}
hwAve = hwAve / 3;
// this loop will ask for three lab grades
for (int l = 0; l < MAXGRADES; l++) {
cout << "Lab grade " << l + 1 << " is ";
cin >> labGrade[s][l]; //lets the user input the LAB grades
labAve += labGrade[s][l];
}
labAve = labAve / 3;
//this loop will ask for three test grades
for (int t = 0; t < MAXGRADES; t++) {
cout << "Test grade " << t + 1 << " is ";
cin >> testGrade[s][t]; //lets the user input the test grades
testAve += testGrade[s][t]; // the average is calculated
}
testAve = testAve / 3;
cout << "Final exam grade: "; // asks user for final exam grade
cin >> feGrade[s];
// equation to get the final course grade
final_num_grade[s] = (hwAve * 0.20) + (labAve * 0.25) + (testAve * 0.30) + (feGrade[s] * 0.25);
line.assign(50, '-');
cout << line << endl;
}
for (int i = 0; i < MAXSTUDENTS; i++) {
cout << "Final Course Grade for " << fName[i] << " " << lName[i] << " with the id " << id[i] << " is " // displays name of student
<< showpoint << fixed << setprecision(1) << final_num_grade[i]; //set to 1 decimal place
//if statement shows the letter grade
if (final_num_grade[i] >= 89.5) { //A if student made 89.5 or more
cout << " (A)\n";
}
else if (final_num_grade[i] >= 79.5) { //B if student made 79.5 to 89.4
cout << " (B)\n";
}
else if (final_num_grade[i] >= 69.5) { // C if student made 69.5 yo 79.4
cout << " (C)\n";
}
else if (final_num_grade[i] >= 59.5) { // D if student made 59.5 to 69.4
cout << " (D)\n";
}
else { // F if student made less than 59.4
cout << " (F)\n";
}
}
return 0;
}
You haven't reset these variables to zero : hwAve, labAve, testAve which makes the second student's grade will be slightly higher
Pretty new here to programming, and I have an assignment where I need to achieve the following:
ask for total amount of people
get each of their names
allow user to enter up to 5 scores for each person
if there are less than 5 scores for a given person, inputting -100 will stop it
So far I have written this:
#include <iostream>
using namespace std;
int main() {
string personName;
int totalPerson, personScoreCounter;
double personGrade, personGradeTotal;
cout << "Input total amount of people: ";
cin >> totalPerson;
for (int person = 1; person <= totalPerson; person++)
{
cout << "Input name for person " << person << ": ";
getline(cin, personName);
cin.ignore();
while ( (personGrade != -100) && (personScoreCounter <= 5) )
{
cout << "Input up to 5 scores for " << personName << " (-100 to end): ";
cin >> personGrade;
if (personGrade >= 0 && personGrade <= 100) // valid range of scores
{
personGradeTotal += personGrade;
personScoreCounter++;
}
else
{
cout << "Input only scores from 0-100" << endl;
}
cout << "Input up to 5 scores for " << personName << " (-100 to end): ";
cin >> personGrade;
}
}
// calculate averages and other stuff in here.
return 0;
}
After getting their name, only the last cout inside the while loop seems to execute first, then it starts from the top and so on until the for loop hits the end depending on totalPerson. I know I'm missing a few things in here, probably in the order of operations and also the way I am executing my loops, but I just can't see it. Could any of you guys with experience in the language please give me any pointers as to what's happening here and how I can fix it? Thank you.
Inside your while group, you only want to use your cout line once (at the beginning looks good).
Your first check should be for ==-100 or similar, since as it is now, you'll get a "Input only scores from 0 to 100" message if you enter -100.
You should keep a cin.ignore(); call after each use of cin >> VARIABLE, since then you will drop the EoL character.
Example code:
#include <iostream>
using namespace std;
int main() {
int totalPerson;
cout << "Input total number of people: ";
cin >> totalPerson;
cin.ignore();
for (int person = 1; person <= totalPerson; person++)
{
int personScoreCounter=0;
double personGrade = -1, personGradeTotal=0;
string personName;
cout << "Input name for person " << person << ": ";
std::getline(cin, personName);
while ( (personGrade != -100) && (personScoreCounter < 5) )
{
cout << "Input up to 5 scores for " << personName << " (-100 to end): ";
cin >> personGrade;
cin.ignore();
if (personGrade == -100) {
break;
} else if (personGrade >= 0 && personGrade <= 100) {
personGradeTotal += personGrade;
personScoreCounter++;
} else {
cout << "Input only scores from 0-100" << endl;
}
}
// calculate averages and other stuff in here.
double avg = personGradeTotal / personScoreCounter;
cout << "Avg = " << avg << endl;
}
return 0;
}
Some of your variables also needed to move inside the for loop.
Additionally I changed the limits on the personScoreCounter to [0:4] rather than [1:5] - this way you can use it for averaging more easily.
You might also try cin.getline() instead of getline(std::cin , ... ):
int max_length = 30;
std::cin.getline(personName, max_length, '\n'); // \n is option termination.
This allows whitespaces in the input also.
http://www.cplusplus.com/reference/istream/istream/getline/
I have an assignment where we need to have 2 parallel arrays one is a list of city names and the other is sales amounts. Here is a copy of the problem:
Program Description:
It needs to compile sales totals for various cities in the USA. Specifically, when the program is run, the user will be prompted to enter a city. If the city is correct, the user will then be prompted to enter a sales amount. If the city doesn’t exist on the list, the user will get an error message (and no sales amount prompt). If a sales amount is entered, it will accumulate into a total for that city. Either way (city exists on the list or not) , the user will then be asked to enter another city or quit.
Once the user quits, the city name and total should be displayed for all cities, one per line. Following that the program should stop.
There are only 8 cities to choose from. 2 parallel arrays must be used, initialized as follows:
City (String) Sales (Integer)
------------- ---------------
Atlanta 0
Buffalo 0
Chicago 0
Dallas 0
Houston 0
Honolulu 0
Miami 0
Reno 0
All input is guaranteed to be single-word followed by enter only. It may not match a city name, but there will be no spaces. This keeps your program simple as it lets you avoid using getline( ), which would be needed to deal with blanks between words.
Sales data is guaranteed good when input.
When I attempted to run my program, visual studios went crazy, and I've pulled out my hair trying to fix it. If someone could help give me some pointers on what I've done wrong, I would greatly appreciate it. Here is a copy of my program:
#include <iostream>
#include <string>
using namespace std;
int main()
{
//declare city and sales array
string city[8] = {" "};
int sales[8] = {0};
//declare variables
string cityName = " ";
int cityTotal = 0;
int salesAmt = 0;
int i = 0;
char another = ' ';
//init city array
city[0] = "Atlanta";
city[1] = "Buffalo";
city[2] = "Chicago";
city[3] = "Dallas";
city[4] = "Houston";
city[5] = "Honololu";
city[6] = "Miami";
city[7] = "Reno";
do
{
//input city name and if found input sales amount
cout << "Enter a City: Atlanta, Buffalo, Chicago, Dallas, Houston, Honololu, Miami, or Reno: ";
cin >> cityName;
for(i = 0; i <= 8; i++)
{
if(cityName == city[i])
{cout << "Enter sales amount: ";
cin >> salesAmt;
salesAmt += sales[i];}
else
{cout << "ERROR: CITY NOT AVAILIABLE" << endl;
cout << endl;}
//end if
}
//end for loop
//ask if another city
cout << "Enter another city?: ";
cin >> another;
} //end do loop
while(another == 'Y' || another == 'y');
{
for(i = 0; i <= 8; i++)
{
cout << "City: " << " " << "Sales: " << endl;
cout << city[i] << " " << sales[i] << endl;
}
//end for loop
} //end while loop
system("pause");
return 0;
} //end of main
A clear error here is the way you have used the index to access the arrays, you can't have the for loop reach 8, as the array's index is only up to 7. change your for loops to:
for(i = 0; i < 8; i++)
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
//declare city and sales array
string city[8] = {" "};
int sales[8] = {0};
//declare variables
string cityName ="";
int cityTotal = 0;
int salesAmt = 0;
int i = 0;
char another = ' ';
//init city array
city[0] = "Atlanta";
city[1] = "Buffalo";
city[2] = "Chicago";
city[3] = "Dallas";
city[4] = "Houston";
city[5] = "Honololu";
city[6] = "Miami";
city[7] = "Reno";
do
{
//input city name and if found input sales amount
cout << "Enter a City: Atlanta, Buffalo, Chicago, Dallas, Houston, Honololu, Miami, or Reno: ";
cin >> cityName;
for(i = 0; i < 8; i++)
{
if(cityName == city[i])
{
cout << "Enter sales amount: ";
cin >> salesAmt;
sales[i] += salesAmt;
} else if (i==7)
{
cout << "ERROR: CITY NOT AVAILIABLE" << endl;
}//end if
}//end for loop
//ask if another city
cout << "Enter another city?: ";
cin >> another;
} //end do loop
while(another == 'Y' || another == 'y');
{
for(i = 0; i < 8; i++)
{
cout << "City: " << " " << "Sales: " << endl;
cout << city[i] << " " << sales[i] << endl;
}
//end for loop
} //end while loop
system("pause");
return 0;
} //end of main
error was for(i = 0; i <= 8; i++) change with for(i = 0; i < 8; i++) and also second for.
Next error changed to sales[i] += salesAmt; and Not salesAmt +=sales[i];.
And your city name is case sensitive when you input city name!