I want to calculate the number of batches of cookies made after a user inputs the number of people. I also want it to round up one digit. But I get 0 when testing the code. What am I doing?
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
double numberOfPeople;
double cookiesPerBatch = 12.0;
double numberOfBatches = ((double)numberOfPeople/cookiesPerBatch);
int main() {
cout << "How many people do you need to serve ?" << endl;
cin >> numberOfPeople;
cout << "You need to make:" << ceil(numberOfBatches) << "batch of cookies" << "\n\n\n\n\n";
Programming isn't the same as writing down the relationships between things.
Everything happens in a specific order.
What you have is out of order.
Program initialization (before main() is called)
1) create a variable numberOfPeople (global variable defaults to value of 0.0)
2) create a variable cookiesPerBatch and assign it a value of 12.0
3) create a varaible numberOfBatches and compute using the variables from steps 1 and 2
Call main()
4) ask user for information
5) set value of variable numberOfPeople
6) print value of variable numberOfBatches
Do you see what went wrong? You computed numberOfBatchesbefore obtaining one of the required values.
Move those variables into main() and make sure to compute stuff in the correct order.
#include <iostream>
#include <cmath>
#include <string>
usingnamespace std;
double numberOfPeople;
double cookiesPerBatch = 12.0;
double numberOfBatches = ((double)numberOfPeople/cookiesPerBatch);
int main()
{
cout << "How many people do you need to serve ?" << endl;
cin >> numberOfPeople;
cout << "You need to make:" << ceil(numberOfBatches)
<< "batch of cookies" << "\n\n\n\n\n";
}
When are the three global variables (on lines 6-8) initialized? Would you believe that it happens before the main() starts?
The expression on line 8, ((double)numberOfPeople/cookiesPerBatch), is computed exactly once, for the initialization.
If that happens before the user has given a new value for numberOfPeople, then you compute 0.0/12.0 every time. (Presumably, I prefer to not know global variables.)
You have to first get the values and then do the calculation:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <cmath>
#include <iostream>
int main()
{
using std::cout;
using std::cin;
cout << "How many people do you need to serve ?\n";
double numberOfPeople;
cin >> numberOfPeople;
double cookiesPerBatch = 12.0;
double numberOfBatches = numberOfPeople / cookiesPerBatch;
cout << "You need to make:" << ceil(numberOfBatches)
<< "batch of cookies\n\n\n\n\n";
}