I have to write a program that uses a for loop to ask how many floors are in a hotel, then ask the user for the number of rooms on each floor and the number of rooms occupied. At the end I'm to add up all the rooms, how many are occupied and not occupied, and give percentages based on those numbers. So far all I have is the loop, and my sum feature now gives me outrageous numbers.
#include <iostream>
using namespace std;
int main ()
{
int floor, room, occupy, total_unoccupy, total_occupy, total_room;
cout << "How many floors are in the hotel?\n";
cin >> floor;
for ( ;floor >= 1; floor--)
{
cout << "How many rooms are on floor " << floor << "?" << endl;
cin >> room;
cout << "How many of these rooms are occupied?" <<endl;
cin >> occupy;
}
total_room += room;
cout << "The total number of rooms are " << total_room << "." << endl;
return 0;
}
Move total_room += room; inside the for loop.
for ( ;floor >= 1; floor--) {
cout << "How many rooms are on floor " << floor << "?" << endl;
cin >> room;
total_room += room;
cout << "How many of these rooms are occupied?" <<endl;
cin >> occupy;
total_occupy += room;
total_unoccupy += room-occupy;
}
Also, you need to change this line:
int floor, room, occupy, total_unoccupy, total_occupy, total_room;
To this:
int floor = 0, room = 0, occupy = 0, total_unoccupy = 0, total_occupy = 0, total_room = 0;
You should initialize the variables like total_occupy = 0 etc... otherwise you can have unexpected results.
Regards
nothing left to be answered thanks for nhgr
Moreover, in case multiplication, you need to initialize the total variable as 1.
Related
How do you use a while loop only to add multiple values with a given point when to exit the loop and display the tallied amounts.
Note the following example. Test your program by entering 7 for the number of items and the following values for the calories: 7 - 120 60 150 600 1200 300 200
If your logic is correct, the following will be displayed: Total calories eaten today = 2630
Below is what I have written, what I require is understanding the calculation for the total calories.
#include <iostream>
using namespace std;
int main()
{
int numberOfItems;
int count = 1; //loop counter for the loop
int caloriesForItem;
int totalCalories;
cout << "How many items did you eat today? ";
cin >> numberOfItems;
cout << "Enter the number of calories in each of the "
<< numberOfItems << " items eaten: " << endl;
while (count <= numberOfItems) // count cannot be more than the number of items
{
cout << "Enter calorie: ";
cin >> caloriesForItem;
totalCalories = ; //?
++count;
}
cout << "Total calories eaten today = " << totalCalories;
return 0;
}
How do I store a value, then add on that value, repeatedly until the program reaches a point to exit as per the count value
Logic Explained
Initialize totalCalories to 0 outside the loop. This is required to prevent undefined behaviour. You may refer to (Why) is using an uninitialized variable undefined behavior? and Default variable value.
For every item, add caloriesForItem to totalCalories. You may also use the += operator if you are familiar with it.
Sourcecode
#include <iostream>
using namespace std;
int main()
{
int numberOfItems;
int count = 1; //loop counter for the loop
int caloriesForItem;
long totalCalories = 0;
cout << "How many items did you eat today? ";
cin >> numberOfItems;
cout << "Enter the number of calories in each of the "
<< numberOfItems << " items eaten: " << endl;
while (count <= numberOfItems) // count cannot be more than the number of items
{
cout << "Enter calorie: ";
cin >> caloriesForItem;
totalCalories = totalCalories + caloriesForItem;
++count;
}
cout << "Total calories eaten today = " << totalCalories;
return 0;
}
Also you can add them with += operator. But the result will be the same.
totalCalories += caloriesForItem;
You should increase the number of total calories in every loop. You can easily do that using the addition assignment operator (+=). It should look like this :
totalCalories += caloriesForItem;
I am trying to get this 'do while' loop to run 3 times and then display the amount in the accumulator contain within a while loop inside the 'do while' loop.
It seems to be counting correctly, but only runs the while loop on the first. When run, instead of going on to ask for the next set of numbers, it just displays the first batch (added up correctly). I have tried switching some of the code around and searching google, but can't find the answer.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int storeNum = 1;
int payRollAmount = 0;
int totalPayroll = 0;
do
{
cout << "Store " << storeNum << ":" << endl;
while (payRollAmount <= -1)
{
cout << "Enter Store's Payroll Amount (-1 to exit): ";
cin >> payRollAmount;
totalPayroll += payRollAmount;
}
storeNum++;
} while (storeNum <= 3);
cout << "The Total Payroll is: " << totalPayroll << endl;
system("pause");
return 0;
}
The code should take in an unknown amount of "payrolls," allow you to exit using -1, and then continue on to the next stores payrolls. It should do this 3 times, and then display the total amount (all numbers entered added together.
Hi perhaps reset payRollAmount at each iteration? That way it will continue to request the input.
for (int amount = 0; amount != -1; ) {
cout << "Enter Store's Payroll Amount (-1 to exit): ";
cin >> amount;
totalPayroll += amount;
}
#include <iostream>
using namespace std;
int main()
{
int score;
int numTests;
int total = 0; //why total has to be set to 0
double average;
cout << "How many tests: ";
cin >> numTests;
int s = 1;
while (s <= numTests)
{
cout << "Enter score # " << s << ": "; // why put the s there ???
cin >> score;
total += score;
s++; //why update the counter
}
cout << "total" << total << endl;
average = (double)total / numTests;
cout << "Average" << average << endl;
system("pause");
return 0;
}
1.My question is that why does the integer total has to be put as value 0? (int total = 0)
2.on the line that I enter the score number why do I have to input the counter s on it? (cout << "Enter score # " << s <<)
3.and why do I have the update the counter (s++)?
Question 1. in c++ and c when you defined a variable the default of value is anything from memory and its not null or 0
Question 2. cout<< is for print data and when you write cout<
Question 3. s++ mean s=s+1; and this is for the loop end while (s <= numTests)
Before you start counting the scores from the tests, naturally the total number is 0.
You put the counter s to indicate which score should be entered, i.e. "score 1", "score 2", etc... It is there for clarification of the user. Imagine you are on the other side and want to see your average from 20 tests, but each time it just shows: "Enter score:" - first, you will not be sure it works, second, at some point you might become distracted and forget how many scores you have entered. So this shows you exactly where you are at.
s++ means each time the counter increases with 1. So, when it reaches the number of tests, the loop will not continue. The counter is used as a condition for the while loop - so that the cycle will stop and not go inifinitely.
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 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)