I'm trying to get it where a user can keep entering the weights/distance of shipment of an item until the user enters zero. The loop will then add up the sum to ship all items entered. Before I add the loop I'm getting the correct calculations. When I add the loop, my total gets to zero no matter what. Whats wrong with my code? I have a calculate charge function I didn't display that I'm calling from.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
int main()
{
double kilograms = 1;
double miles = 0;
double total = 0;
while (kilograms <= 0)
{
cout << "Please enter weight for item" << endl;
cin >> kilograms;
cout << "Please enter distance for shippment" << endl;
cin >> miles;
total = calculateCharge(kilograms, miles, total);
}
Maybe you want to not compare the value of kilograms to zero (0) or greater for that condition to be true but compare the value of kilograms to only that is greater then zero (0) for the condition to be true.
So for instance it would look like: while (kilograms > 0) {...}
not: while (kilograms => 0) {...}
or: while (kilograms <= 0) {...}
or: while (kilograms != 0) {...}
Your total variable isn't a total. It is the result of the last calculation. When you enter a kilograms value of 0 I am guessing you also enter a miles value of 0 and the resulting calculation's result is 0.
double kilograms = 0; // Can be 0. Makes no difference
double miles = 0;
double total = 0;
while (true) // Changed from <= 0. If kept should be kilograms > 0
{
CLS; // A #define CLS system("cls")
cout << "Please enter weight for item" << endl;
cin >> kilograms;
if (kilograms == 0) break; // Needs to be chedked here. Otherwise you will have to enter miles
// before the while condition would check for zero. Otherwise the output would be 0.00.
cout << "Please enter distance for shippment" << endl;
cin >> miles;
total = calculateCharge(kilograms, miles, total);
// Added to see the output. Add setpersion(0) before miles to leave off decimal point.
std::cout << fixed << setprecision(2) << "\n Total charge is: " << total << " for a shipment of " << kilograms << " kilograms for a distance of " << setprecision(0) << miles << " miles." << endl;
// Added to pause program to see output before CLS changee to what you like.
cout << "\n\n\n\nFin Press any key to continue -- > ";
_getch();
}