- #1
Lord Anoobis
- 131
- 22
Homework Statement
A kilogram is 1000 grams. Write a program that will read the weight of a package of butter in grams and output the weight in kilograms, as well as the number of packages of butter needed to yield 1 kilogram of butter. Your program should allow the user to repeat this calculation as often as the user wishes.
Homework Equations
The Attempt at a Solution
/*Converts a package of butter from grams to kilograms and
calculates the number of packages needed to make up at least 1 kilogram*/
#include <iostream>
using namespace std;
int main()
{
const float kilo = 1000; //grams per kg
float total_weight = 0, weight_g, weight_kg;
int packages = 0;
cout << "Enter the weight of the package of butter in grams: ";
cin >> weight_g;
cout.setf(ios::fixed);
cout.precision(3);
while (weight_g != 0)
{
weight_kg = weight_g/kilo; // convert to kg
cout << endl << "The weight of the package in kilograms is: "
<< weight_kg << "kg" << endl;
while (total_weight < 1000) // counting the packages required
{
total_weight = total_weight + weight_g;
packages++;
}
cout << "For at least 1 kilogram of butter you need "
<< packages << " packages." << endl;
cout << "Enter another package weight to continue or enter 0 to "
<< "end the program." << endl << endl
<< "Package weight: ";
cin >> weight_g;
}
return 0;
}
The program works in all aspects but one, crucial too. The number of packages required is correct for the first figure entered, but carries over for any other value. So it stays, for example, 5 packages for 200g. I'm sure I'm missing something simple here but I just don't see it. The compiler used is Codeblocks. Please assist.