Solve Beginner C++ Hassles: Convert Grams to Kilograms

  • Context: Comp Sci 
  • Thread starter Thread starter Lord Anoobis
  • Start date Start date
  • Tags Tags
    Beginner C++
Click For Summary

Discussion Overview

The discussion revolves around a C++ programming assignment that requires converting grams to kilograms and calculating the number of packages needed to make up at least one kilogram of butter. Participants explore issues related to variable initialization and program flow, focusing on debugging the code provided.

Discussion Character

  • Homework-related
  • Technical explanation
  • Debate/contested

Main Points Raised

  • One participant notes that the number of packages required is correct for the first input but carries over for subsequent values, indicating a potential issue with variable resetting.
  • Another participant suggests considering the value of 'total_weight' during iterations and questions whether it is reset between calculations.
  • There is a suggestion to use code formatting for better readability.
  • A participant proposes that the problem may lie in the second while loop, which may not execute on subsequent iterations due to the value of 'total_weight'.
  • One participant identifies that after the first calculation, 'total_weight' retains its value, preventing the second while loop from executing, thus affecting the 'packages' count.
  • Another participant confirms that reinitializing 'total_weight' and 'packages' resolves the issue, while also questioning if there is a simpler approach to the program.
  • Suggestions are made to consider alternative methods for calculating the number of packages, including using mathematical approaches or different loop structures.
  • Participants discuss the types of loops available in C++ and their appropriate use cases, suggesting that a do/while loop might fit the problem better.

Areas of Agreement / Disagreement

Participants generally agree on the need to reset certain variables to avoid carryover issues, but there is no consensus on the best overall approach to simplify the program.

Contextual Notes

Participants mention potential multiple errors in the code, with at least two issues being masked by the current problem. There is an emphasis on the importance of understanding variable states during program execution.

Who May Find This Useful

This discussion may be useful for beginners in C++ programming, particularly those facing challenges with variable management and loop structures in coding assignments.

Lord Anoobis
Messages
131
Reaction score
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;
count << "Enter the weight of the package of butter in grams: ";
cin >> weight_g;
count.setf(ios::fixed);
count.precision(3);

while (weight_g != 0)
{
weight_kg = weight_g/kilo; // convert to kg
count << 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++;
}

count << "For at least 1 kilogram of butter you need "
<< packages << " packages." << endl;
count << "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.
 
Physics news on Phys.org
Lord Anoobis said:
The number of packages required is correct for the first figure entered, but carries over for any other value.
Disregarding possible optimizations :wink:, consider what value 'total_weight' has as you iterate - does it ever get reset?

You can use [ code ][ /code] tags (without the spaces) to make your code more legible.
 
milesyoung said:
Disregarding possible optimizations :wink:, consider what value 'total_weight' has as you iterate - does it ever get reset?

You can use [ code ][ /code] tags (without the spaces) to make your code more legible.
It seems that total_weight is using the same initial value on each pass. I can't see why the new value is used for the conversion but gets tossed for the number of packages though. I get the feeling it has to do with the second while loop, right?
 
Lord Anoobis said:
It seems that total_weight is using the same initial value on each pass. I can't see why the new value is used for the conversion but gets tossed for the number of packages though. I get the feeling it has to do with the second while loop, right?

Yes and no. Try this. On a piece of paper set up all your variables and walk through the code updating the variables by hand. Do only what the code tells you to do. Might point out your problem.

Or alternatively

When facing a coding bug try and ask yourself when does the bug happen and when does it not happen?
In your case you say it works for the first time but not the subsequent times.
So what does your code do on the first run that it doesn't on the next time through?? (Hint you actually have at least 2 of these errors but one is being masked by the current issue you're having :wink:)
 
Lord Anoobis said:
It seems that total_weight is using the same initial value on each pass.
After you've calculated the first package count, then 'total_weight' might, for instance, have the value 1005. As you encounter the while loop a second time, 'total_weight < 1000' evaluates to false, and you'll never enter the loop again, i.e. 'packages' will always have the value of the first count.

Lord Anoobis said:
I can't see why the new value is used for the conversion but gets tossed for the number of packages though.
You're talking about 'weight_g'? It does change, but since you effectively disable the second while loop, it makes no difference.
 
milesyoung said:
After you've calculated the first package count, then 'total_weight' might, for instance, have the value 1005. As you encounter the while loop a second time, 'total_weight < 1000' evaluates to false, and you'll never enter the loop again, i.e. 'packages' will always have the value of the first count.You're talking about 'weight_g'? It does change, but since you effectively disable the second while loop, it makes no difference.
Damn. Talk about being in plain sight. Reinitializing total_weight and packages solves the problem. Is there a simpler way of going about this program as a whole
cpscdave said:
Yes and no. Try this. On a piece of paper set up all your variables and walk through the code updating the variables by hand. Do only what the code tells you to do. Might point out your problem.

Or alternatively

When facing a coding bug try and ask yourself when does the bug happen and when does it not happen?
In your case you say it works for the first time but not the subsequent times.
So what does your code do on the first run that it doesn't on the next time through?? (Hint you actually have at least 2 of these errors but one is being masked by the current issue you're having :wink:)

?
 
cpscdave said:
Yes and no. Try this. On a piece of paper set up all your variables and walk through the code updating the variables by hand. Do only what the code tells you to do. Might point out your problem.

Or alternatively

When facing a coding bug try and ask yourself when does the bug happen and when does it not happen?
In your case you say it works for the first time but not the subsequent times.
So what does your code do on the first run that it doesn't on the next time through?? (Hint you actually have at least 2 of these errors but one is being masked by the current issue you're having :wink:)
Checking it on paper certainly did make things clearer. The packages counter issue is quite well hidden behind the other. I'll be sure to do the paper check more often in future.
 
Lord Anoobis said:
Damn. Talk about being in plain sight. Reinitializing total_weight and packages solves the problem. Is there a simpler way of going about this program as a whole?
Whoops. Dunno what happened there. Time to hit the deck I think.
 
Glad you got what I was trying to get at :D

To answer your questions yes there are couple other ways you can solve this problem.

Is there a way you can figure out the number of packages required using only math? Think how you would solve this problem yourself :)

Also you could write the over all program flow using a do/while loop as opposed to a while loop.

I usually tell people there are 3 basic looping types
For loops (when you want to run the loop an known number of times)
do while loops (when you want to run the loop at least one time and until a condition is met)
while loops (when you want to run the loop until a condition is met)

This seems to fit the 1 time and until condition is met.
 

Similar threads

  • · Replies 2 ·
Replies
2
Views
3K
  • · Replies 3 ·
Replies
3
Views
1K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 24 ·
Replies
24
Views
2K
  • · Replies 9 ·
Replies
9
Views
3K
  • · Replies 23 ·
Replies
23
Views
3K
  • · Replies 13 ·
Replies
13
Views
2K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 6 ·
Replies
6
Views
3K
  • · Replies 5 ·
Replies
5
Views
4K