Reputation: 21
I'm doing another coding exercise and my code is not giving me correct answers.
For example:
What was the total amount of milk produced in the morning: 3590.56
Below is my code
#include<iostream>
#include<string>
#include<iomanip>
#include<fstream>
using namespace std;
const double CARTON = 3.78;
const double PRODUCECOST = 0.38;
const double PROFIT = 0.27;
int main() {
double milkProduced, numCartons;
double costOfProducing, profitOfProducing;
cout << fixed << showpoint << setprecision(2);
cout << "What was the total amount of milk produced in the morning: " << endl;
cin >> milkProduced;
numCartons = milkProduced / CARTON;
costOfProducing = milkProduced * PRODUCECOST;
profitOfProducing = numCartons * PROFIT;
cout << static_cast<int>(numCartons) << endl;
cout << costOfProducing << endl;
cout << profitOfProducing << endl;
return 0;
}
Upvotes: 0
Views: 91
Reputation: 882686
That's very close, but your num_cartons
value is actually 949.883...
and, when you cast that to an int
, it truncates the fractional part rather than rounding it.
In addition, you only do that for the output and do not feed that change back into the variable for the subsequent calculations (specifically, the profit).
I suggest, rather than doing that, you try:
numCartons = round(milkProduced / CARTON); // needs <cmath>
to set the value.
That will make the number of cartons an integral value, or close enough for classwork assignments. In other words:
#include<iostream>
#include<string>
#include<iomanip>
#include<fstream>
#include<cmath>
using namespace std;
const double CARTON = 3.78;
const double PRODUCECOST = 0.38;
const double PROFIT = 0.27;
int main() {
double milkProduced, numCartons;
double costOfProducing, profitOfProducing;
cout << fixed << showpoint << setprecision(2);
cout << "What was the total amount of milk produced in the morning: " << endl;
cin >> milkProduced;
numCartons = round(milkProduced / CARTON);
costOfProducing = milkProduced * PRODUCECOST;
profitOfProducing = numCartons * PROFIT;
cout << numCartons << endl;
cout << costOfProducing << endl;
cout << profitOfProducing << endl;
return 0;
}
The output of that is more in line with what you expect:
> ./testProg
What was the total amount of milk produced in the morning: 3590.56
950.00
1364.41
256.50
As pointed out in the comments, you possibly should be truncating rather than rounding down, since you can most likely not sell a partially filled container (or add water if you're, shall we say, ethically ambiguous).
However, even if that is the case, you should modify the variable so that it affects the profit figure, rather than just outputting the rounded value and using the original.
I've only rounded since you stated that 950
was the correct carton count.
Upvotes: 2