Why do I have to enter twice? - c++

I trying to write a simple program for school and I have a bit of problem. I have to enter twice for it work right.
for example i have input 3 two time for it to give me 90..
What can i do to fix it.
Does the coding look right at the moment
#include <iostream>
#include <string>
using namespace std;
int main(){
string Cartype, rateoption;
double total, miles, days;
const double CdailyRate=30;
const double PdailyRate=40;
const double FdailyRate=50;
const double CmileRate=0.25;
const double PmileRate=0.35;
const double FmileRate=0.45;
cout<<"Thank you for choosing Car Rite Rental for your rental needs!\n"
<<"\a Before we get started calculating your total owed please remember\n"
<<"that here at Car Rite Rental we havea MINIMUM PAYMENT OF $30.\n\n"
<<"Please enter the type of car you have rented: \n\n"
<<"[please enter corresponding letter] \n"
<<"C-Chevrolet\n"<<"P-Pontiac\n"<<"F-Ford\n";
cin>>Cartype;
cout<<"Please choose your payment option from the following: \n\n"
<<"[please enter corresponding number] \n"
<<"D-Daily Rate\n"<<"M-Mileage Rate\n";
cin>>rateoption;
if(rateoption=="D"||rateoption=="d"){
cout<<"Please enter the number of days you have rented this vehicle: \n";
cin>>days;
}
else
cout<<"Please enter the number of miles traveled in your rental car:\n";
cin>>miles;
if (Cartype=="C"||Cartype=="c" && rateoption=="D"||rateoption=="d"){
total=CdailyRate*days;
cout<<"Your total owed today is: $"<<total<<"\nThank you again for choosing Car Rite Rental!\n";
}
return 0;
}

Because you have a missing set of braces.
else
cout<<"Please enter the number of miles traveled in your rental car:\n";
cin>>miles;
Although it's indented, the "cin>>miles;" statement is always executed, it is not conditional on the else.
else {
cout<<"Please enter the number of miles traveled in your rental car:\n";
cin>>miles;
}
will fix it.

Related

Logical error in outputting a room discount

I have been smashing my head against my keyboard for days and haven't gotten any help in any of my usual places. Someone please wave a wand and tell me what I'm doing wrong! When I run my code I get proper output for up to 19 rooms, once 20 is hit it's not outputting a discount. I have tried to rewrite the "if" statements several different ways and even went to a switch/break setup and it's the same issue every single time. I have a logical error and CANNOT find it!
The assignment is "The cost of renting a room at a hotel is, say $100.00 per night. For special occasions, such as a wedding or conference, the hotel offers a special discount as follows.
If the number of rooms booked is:
at least 10, the discount is 10%
at least 20, the discount is 20%
at least 30, the discount is 30%
Also if rooms are booked for at least three days, then there is an additional 5% discount.
Instructions
Write a program that prompts the user to enter:
The cost of renting one room
The number of rooms booked
The number of days the rooms are booked
The sales tax (as a percent).
The program outputs:
The cost of renting one room
The discount on each room as a percent
The number of rooms booked
The number of days the rooms are booked
The total cost of the rooms
The sales tax
The total billing amount.
My code is
#include<iostream>
#include<`iomanip`>
`using namespace std`;
`int main`()
{
const float discount_10=0.10;
const float discount_20=0.20;
const float discount_30=0.30;
const float additional_discount=0.05;
cout << fixed << showpoint;
cout << setprecision(2);
//Variables
double total_discount, final_bill, tax, base_cost, total_cost, room_cost, sales_tax;
int num_rooms, num_of_days;
cout<<"Enter the cost of renting one room: $";
cin>>base_cost;
cout<<"Enter the number of rooms booked: ";
cin>>num_rooms;
cout<<"Enter number of days the rooms are booked: ";
cin>>num_of_days;
cout<<"Enter sales tax(%): ";
cin>>sales_tax;
if(num_rooms>=30)
total_discount = discount_30;
else if(num_rooms>=20 && num_rooms<=29)
total_discount = discount_20;
else if(num_rooms>=10 && num_rooms<=19)
total_discount = discount_10;
else if (num_rooms >=9)
total_discount =0;
if(num_of_days>=3)
total_discount += additional_discount;
else if (num_of_days<3)
total_discount = 0;
room_cost = (base_cost * num_of_days * num_rooms);
//Total cost for all rooms
total_cost = room_cost - (room_cost * total_discount);
tax = total_cost * (sales_tax/100);
//Final bill
final_bill=total_cost+tax;
cout<<"Cost of one room:" << base_cost <<endl;
cout<<"Discount:" << total_discount *100<<"%"<<endl;
cout<< "Rooms booked:" << num_rooms <<endl;
cout<<"Days booked: " << num_of_days <<endl;
cout<<"Total Cost: $" << total_cost<<endl;
cout<<"Sales tax: "<<tax<< "%"<< endl;
cout<<"Total bill: $" << final_bill << endl;
return 0;
}
I've rewritten this thing about a dozen times and can't find it. I'm going nuts.

Why does this C++ program not display a float for the first output?

I'm curious as to why C++ does not display an output as a float if the code block is the first block in a series of code blocks. Let me explain...Take this example:
#include <iostream>
#include<iomanip>
using namespace std;
int main()
{
double miles;
double fahrenheit;
double gallons;
double pounds;
double inches;
const double milesToKilometers=1.60;
const double fahrenheitToCelsius=5.0/9.0;
const double gallonsToLiters=3.9;
const double poundsToKilograms=0.45;
const double inchesToCentimeters=2.54;
// Get miles, then convert from miles to kilometers.
cout << "Please tell me how many miles you want converted to kilometers:
";
cin >> miles;
if (miles < 0)
cout<<"You cannot enter negative numbers. Please run the program a
again and enter valid number." <<endl<<endl;
else
cout<<miles<<" miles is equal to "<<setprecision(2)
<<fixed<<miles*milesToKilometers<<" kilometers.\n\n";
// Get fahrenheit, then convert from fahrenheit to celsius.
cout << "Please tell me how many degrees fahrenheit you want converted to
celsius: ";
cin >> fahrenheit;
if(fahrenheit < 0)
cout<<"You cannot enter negative numbers. Please run the program again
and enter valid number." <<endl<<endl;
else if(fahrenheit > 1000)
cout<<"You cannot enter numbers above 1000. Please run the program again
and enter valid number." <<endl<<endl;
else
cout<<fahrenheit<<" degree fahrenheit is equal to "<<setprecision(2)
<<fixed<< (fahrenheit-32)*fahrenheitToCelsius <<" celsius.\n\n";
// Get gallons, then convert from gallons to liters.
cout << "Please tell me how many gallons you want converted to liters: ";
cin >> gallons;
if (gallons < 0)
cout<<"You cannot enter negative numbers. Please run the program again
and enter valid number." <<endl<<endl;
else
cout<<gallons<<" gallons is equal to "<<setprecision(2)
<<fixed<<gallons*gallonsToLiters<<" liters.\n\n";
// Get pounds, then convert from pounds to kilograms.
cout << "Please tell me how many pounds you want converted to kilograms: ";
cin >> pounds;
if (pounds < 0)
cout<<"You cannot enter negative numbers. Please run the program again
and enter valid number." <<endl<<endl;
else
cout<<pounds<<" pounds is equal to "<<setprecision(2)
<<fixed<<pounds*poundsToKilograms<<" kilograms.\n\n";
// Get inches, then convert from inches to centimeters.
cout << "Please tell me how many inches you want converted to centimeters:
";
cin >> inches;
if (inches < 0)
cout<<"You cannot enter negative numbers. Please run the program again
and enter valid number." <<endl<<endl;
else
cout<<inches<<" inches is equal to "<<setprecision(2)
<<fixed<<inches*inchesToCentimeters<<" centimeters.\n\n";
return 0;
}
If you run this, and enter any number of miles, (e.g. 10 miles) this first code output will display:
Please tell me how many miles you want converted to kilometers:10
//input>>10
10 miles is equal to 16.00 kilometers.
Notice the output says 10 miles not 10.00. Now observe the remaining outputs:
if you enter 10 for the remaining code blocks, 'fahrenheit to Celsius,' ' Gallons to Liters', 'Inches to Centimeters,' the output will display 10.00, not 10. In addition, if you transpose the order of code blocks, (e.g. make 'miles to kilometers' the second code block instead of the first code block), the first code block will always display an int (e.g. 10) instead of a float (e.g. 10.00).
What's up with this?
The default is that floating-point values that represent exact integer values are displayed without a decimal point and without any digits to the right of the (not-displayed) decimal point. That's why the first one is 10. After inserting setprecision(2), floating-point values are all displayed with a decimal point and two digits to the right of the decimal point. That's why the rest are 10.00. If you want the first one to be shown as 10.00, move the insertion of setprecision(2) so that it's done before displaying the first value.
You’re declaring your variables at double; try declaring them as a float that way it will support decimals from the get-go and you’ll have no need to use setprecision(n). But! If one of your numbers comes back with a billion numbers after the decimal and you want to limit the amount of numbers that follow the decimal, go ahead and toss setprecision(n) back in there.

Do while Loops not working

I've been recycling an assignment to further practice and develop my programming skills in my class and I'm having an issue with 3 DO WHILE loops within another Do While loop.
I'm trying to deny Test scores for test1, 2 and 3 that are less than 1 and greater than 100.
I'm encountering that the loops are not processing what I am inputting for Test1/2/3. It's allowing values out of the while range to pass through. Is there anyone who can suggest or see what I might be doing wrong? Thanks ahead of time guys!
#include<iostream>
#include<cmath>
#include<iomanip>
using namespace std;
double computeavg (int a, int b, int c);
char lettergrade (double z);
int main ()
{
double test1, test2, test3, average; //test1/2/3, test scores, Average: average of test scores
double tottest1=0, tottest2=0, tottest3=0, avg1, avg2, avg3; //tottest# - sum of test grades collected for that number test, avg# average for first second or third test
int student=0, avgvar; //average variable, Student number
char grade, ans; // Holds a letter grade, holds a response to a question
do{
student=student+1;
cout<<"Hello Student #"<<student<<endl;
do{
cout<<"Please input test 1 Grade ";
cin>> test1;
}
while(test1>=1||test1<=100);
do{
cout<<"Please input test 2 Grade ";
cin>> test2;
}
while(test2>=1||test2<=100);
do{
cout<<"Please input test 3 Grade ";
cin>> test3;
}
while(test3>=1||test3<=100);
average=computeavg (test1, test2, test3);
cout<<setprecision(0)<<fixed;
cout<<"Your Average is: "<<average<<endl;
tottest1=tottest1+test1;
tottest2=tottest2+test2;
tottest3=tottest3+test3;
grade = lettergrade(average);
cout << "Your grade is " << grade << endl;
cout<<"Do you want to grade another student? (y/n)";
cin>>ans;
cout<<"\n";
} while(ans=='y');
I think you need to change do while as below:
do{
cout<<"Please input test 1 Grade ";
cin>> test1;
}
while(test1<1||test1>100);
Your conditions are backward. Look carefully: while(test3>=1||test3<=100). All numbers satisfy at least a portion of the condition. For example, −4 is not greater than or equal to 1, but it is less than or equal to 100, and since your conditions are joined with the || operator, which is the or operator, the condition evaluates to true.
You need to change the condition. This is homework, so I won't tell you precisely what condition you should use instead.
You can use a debugger to discover this problem yourself. You can also discover it by carefully walking through your program by hand. Get a pencil and some paper, and write down the current values of your variables. Keep track of which instruction you're on, and then work your way through the program. When a variable changes, cross out its old value and write down the new one. Eventually, you'll be able to do that in your head, but while you're learning, it helps to just write it down.

For-loop not traversing through array correctly. (Option 3

The for loop in function "studScore" is printing out the incorrect grade letter after entering the grades for each student. This is not the complete code.
After selecting option 1 and inputting the grades for the students. Selecting option 3 and outputs the same letter grade for each student.
#include <iostream>
using namespace std;
int students;
double average;
int grade[300][6];
int score;
void letter();
double studScore();
double classave();
int stud;
int main()
{
int choice;
int choice1;
cout<< "Student project Database"<<endl<<endl<<endl;
do {
cout<< "Please choose an option."<<endl;
cout<< "1. To store the scores for students' quizzes. "<<endl;
cout<< "2. To compute the class average on a specific quiz."<<endl;
cout<< "3. To see the letter grade of a specific student."<<endl;
cout<< "4. To compute the overall class average in the course."<<endl;
cout<< "Press 0 to quit."<<endl;
cout<< "Please choose: ";
cin>> choice;
cout<<endl;
}
while (choice!=1);
if (choice==1){
cout<<"Please give the number of students: ";
cin>>students;
for (i =0; i<students;i++){
for (j=0; j<6; j++){
cout<<"Please give the score of student "<<(i+1)<<" in quiz "<<(j+1)<<": ";
cin>>score;
grade[i][j]=score;
}
}
cout<<endl;
do {
cout<< "Please choose an option."<<endl;
cout<< "1. To store the scores for students' quizzes. "<<endl;
cout<< "2. To compute the class average on a specific quiz."<<endl;
cout<< "3. To see the letter grade of a specific student."<<endl;
cout<< "4. To compute the overall class average in the course."<<endl;
cout<< "Press 0 to quit."<<endl;
cout<< "Please choose: ";
cin>> choice1;
cout<<endl;
if (!cin){
cin.clear();
cin.ignore();
cout<<"Invalid choice. Only options 0-4 are allowed."<<endl<<endl;
}
else if (choice1==3){
cout<<"Please give the student #: ";
studScore();
letter();
}
else if (choice1==4){
cout<<"The class average is "<<c_ave;
}
}
while(choice1!=0&&choice==1);
}
return 0;}
cout<<endl;
return average;
double studScore(){
int sum=0;
cin>>stud;
if(stud>i){
cout<<"Invalid choice for student #"<<endl<<endl;
return 0;
}
for(i=stud-1; i<=stud-1;i++){
for(j=0;j<6;j++){
sum+=grade[i][j];
ave2=(sum/6);
}
return ave2;
}
}
void letter(){
if (ave2>=93&&ave2<=100)
cout<<"The letter grade for student "<<(stud)<<" is A"<<endl<<endl;
if(ave2>=87 && ave2<93)
cout<<"The letter grade for student "<<(stud)<<" is A-"<<endl<<endl;
if(ave2>=83&&ave2<87)
cout<<"The letter grade for student "<<(stud)<<" is B+"<<endl<<endl;
if(ave2>=80&&ave2<83)
cout<<"The letter grade for student "<<(stud)<<" is B"<<endl<<endl;
if(ave2>=77&&ave2<80)
cout<<"The letter grade for student "<<(stud)<<" is B-"<<endl<<endl;
if(ave2>=73&&ave2<77)
cout<<"The letter grade for student "<<(stud)<<" is C+"<<endl<<endl;
if(ave2>=70&&ave2<73)
cout<<"The letter grade for student "<<(stud)<<" is C"<<endl<<endl;
if(ave2>=67&&ave2<70)
cout<<"The letter grade for student "<<(stud)<<" is C-"<<endl<<endl;
if(ave2<67)
cout<<"Student "<<(stud)<<" failed the course."<<endl<<endl;
}
Some sample output
Please choose an option.
1. To store the scores for students' quizzes.
2. To compute the class average on a specific quiz.
3. To see the letter grade of a specific student.
4. To compute the overall class average in the course.
Press 0 to quit.
Please choose: 1
Please give the number of students: 3
Please give the score of student 1 in quiz 1: 95
Please give the score of student 1 in quiz 2: 95
Please give the score of student 1 in quiz 3: 95
Please give the score of student 1 in quiz 4: 95
Please give the score of student 1 in quiz 5: 95
Please give the score of student 1 in quiz 6: 95
Please give the score of student 2 in quiz 1: 80
Please give the score of student 2 in quiz 2: 80
Please give the score of student 2 in quiz 3: 80
Please give the score of student 2 in quiz 4: 80
Please give the score of student 2 in quiz 5: 80
Please give the score of student 2 in quiz 6: 80
Please give the score of student 3 in quiz 1: 56
Please give the score of student 3 in quiz 2: 56
Please give the score of student 3 in quiz 3: 56
Please give the score of student 3 in quiz 4: 56
Please give the score of student 3 in quiz 5: 56
Please give the score of student 3 in quiz 6: 56
Please choose an option.
1. To store the scores for students' quizzes.
2. To compute the class average on a specific quiz.
3. To see the letter grade of a specific student.
4. To compute the overall class average in the course.
Press 0 to quit.
Please choose: 3
Please give the student #: 2
The letter grade for student 2 is B
Please choose an option.
1. To store the scores for students' quizzes.
2. To compute the class average on a specific quiz.
3. To see the letter grade of a specific student.
4. To compute the overall class average in the course.
Press 0 to quit.
Please choose: 3
Please give the student #: 3
Invalid choice for student #
The letter grade for student 3 is B
I think it's because you're not setting sum to 0 at the start of studScore().
Also, you need to use more functions (with more parameters), much fewer global variables and you should try to avoid printing things from within functions. E.g. letter() should have a parameter called int average and return a char. If you want, have a separate function called print_student_grade() that takes a int student parameter, calls studScore() and letter() and then prints the output.
Seriously, lots of functions. And I find that it's good to split them between source files based on the sub-problem that they solve.
And 90% of your global variables should be moved to a local variable in a function.

Cant figure out how to calculate individual students totals in a loop

I am having an issue with this program. I need it to ask for a user id then ask for book code and then the cost of a book. An individual can enter an unknown number of books. the program needs to then calculate the individual students book total and then ask another student who does the same. the program must then display the grand totals and total number of books. I cant seem to figure out what to use to be able to keep track of the individual students entries. I would be able to do this from what I was reading about arrays. But we are not to that point yet. The professor wants us to do this with a loop. I am so lost, any help would be awesome.
#include <iostream>
#include <iomanip>
using namespace std;
int main ()
{
//Declare Variables.
int student_id;
char book_code;
float book_cost;
float tax_amount;
float book_subtotal;
const int SENTINEL = -9999;
const double TAX = .07;
float total_book_cost;
int number_books;
int total_books_sold;
double grand_total;
//Set Variables to Zero.
number_books = 0;
total_book_cost = 0.00;
grand_total = 0.00;
//Set Decimal to two places.
cout << fixed << showpoint;
cout << setprecision(2);
//Input Data
cout<<"Please enter your Student ID, then press enter."<<endl;
cin>>student_id;
while (student_id != SENTINEL){
cout<<"Please enter your Book Code, then press enter."<<endl;
cin>>book_code;
cout<<"Please enter the cost of the book, then press enter."<<endl;
cout<<"$"; cin>>book_cost;
tax_amount = book_cost * TAX;
book_subtotal = book_cost + tax_amount;
total_book_cost += book_subtotal;
number_books++;
cout<<"\tStudent Textbook Purchases Report"<<endl;
cout<<"********************************************"<<endl;
cout<<"Student"<<"\tBook"<<"\tBook"<<"\tTax"<<"\tBook"<<endl;
cout<<"Id"<<"\tCode"<<"\tCost"<<"\tAmount"<<"\tSubtotal"<<endl;
cout<<"--------------------------------------------"<<endl;
cout<<student_id<<setw(5)<<book_code<<setw(8)<<"$"<<book_cost<<
setw(3)<<"$"<<tax_amount<<setw(4)<<"$"<<book_subtotal<<endl;
cout<<endl;
cout<<"Total number of books purchased:"<<setw(8)<<number_books<<endl;
cout<<"Total books cost including tax:"<<setw(9)<<"$"<<total_book_cost<<endl;
cout<<"Please enter your Student ID, then press enter."<<endl;
cin>>student_id;
}
grand_total += total_book_cost;
total_books_sold += number_books;
cout<<"**************************************************"<<endl;
cout<<"Grand Totals:"<<endl;
cout<<"Total number of students who purchased books:"<<endl;
cout<<"Total number of books sold:"<<endl;
cout<<"Total cost of all books and taxes:"<<setw(9)<<"$"<<grand_total<<endl;
//Can put grand totals here
system("Pause");
return 0;
}
You could use the loop as this:
#include <iostream>
#include <iomanip>
using namespace std;
int main ()
{
//Set Decimal to two places.
cout << fixed << showpoint;
cout << setprecision(2);
int total_books_sold = 0;
double grand_total = 0.0;
const int SENTINEL = -9999;
int student_id = SENTINEL;
//Input Data
cout<<"Please enter your Student ID, then press enter."<<endl;
cin>>student_id;
while (student_id != SENTINEL){
double total_book_cost = 0.0;
int number_books = 0;
char book_code = '\0';
while (true)
{
cout<<"Please enter your Book Code, then press enter."<<endl;
cin>>book_code;
if (book_code == 'x')
break;
float book_cost;
cout<<"Please enter the cost of the book, then press enter."<<endl;
cout<<"$"; cin>>book_cost;
const double TAX = .07;
double tax_amount = book_cost * TAX;
double book_subtotal = book_cost + tax_amount;
total_book_cost += book_subtotal;
number_books++;
cout<<"\tStudent Textbook Purchases Report"<<endl;
cout<<"********************************************"<<endl;
cout<<"Student"<<"\tBook"<<"\tBook"<<"\tTax"<<"\tBook"<<endl;
cout<<"Id"<<"\tCode"<<"\tCost"<<"\tAmount"<<"\tSubtotal"<<endl;
cout<<"--------------------------------------------"<<endl;
cout<<student_id<<setw(5)<<book_code<<setw(8)<<"$"<<book_cost<<
setw(3)<<"$"<<tax_amount<<setw(4)<<"$"<<book_subtotal<<endl;
cout<<endl;
};
grand_total += total_book_cost;
total_books_sold += number_books;
cout<<"Total number of books purchased:"<<setw(8)<<number_books<<endl;
cout<<"Total books cost including tax:"<<setw(9)<<"$"<<total_book_cost<<endl;
cout<<"Please enter your Student ID, then press enter."<<endl;
cin>>student_id;
}
cout<<"**************************************************"<<endl;
cout<<"Grand Totals:"<<endl;
cout<<"Total number of students who purchased books:"<<endl;
cout<<"Total number of books sold:"<<endl;
cout<<"Total cost of all books and taxes:"<<setw(9)<<"$"<<grand_total<<endl;
//Can put grand totals here
system("Pause");
return 0;
}