Reputation: 83
I'm currently learning C# and I'm trying to find out how declare a variable to hold a sum and increment this variable each time through a while loop. My goal is to ask how many packages the user wants to ship, then get the weight for each package (using a while loop). The issue is how to take the input for each input (however many packages the user has dictated to send) and assign it to a variable without overriding the last entry in the while loop while adding them all together and displaying the combined about as "total".
static void Main(string[] args)
{
Console.WriteLine("Package Shipping Calculator");
//ask user how many packages they want to ship
Console.Write("How many packages would you like to ship? ");
string userinput = Console.ReadLine();
string userinput2;
double result;
double total=0;
//create loop for weight in lbs that the package weighs. Multiply $2.35 per pound (weight*2.35)
//for each increment, then add the result
int counter = 1;
while (counter <= int.Parse(userinput))
{
Console.Write("Please enter the weight of package {0}: ", counter);
userinput2 = Console.ReadLine();
result = double.Parse(userinput2) * 2.35;
counter++;
}
counter --;
Console.Write("\nThe cost to ship {0} packages is {1:C}", counter, total);
Console.ReadKey();
}
As you can see, I have the counter going to ask how many times it needs to ask for the weight, but I don't know how to take the amount for each package and add them together inside of the loop. I would greatly appreciate help with this. Thanks in advance.
Upvotes: 3
Views: 879
Reputation: 83
Thanks to the great recommendations combined, I was able to find the answer to my question. I changed result = double.Parse(userinput2) * 2.35;
to result += double.Parse(userinput2) * 2.35;
and then declared my variable result=0
as before it was not assigned a value. I removed total
from my final Write line as the method I changed to no longer needed it.
Upvotes: 0
Reputation: 232
In you code add
total = total + result;
right after
result = double.Parse(userinput2) * 2.35;
Upvotes: 1
Reputation: 31
I have to say, you're really close. The only thing I could suggest is that you add the previous amount of result
to itself each time it's goes through it's loop. Such as
while (counter <= int.Parse(userinput))
{
Console.Write("Please enter the weight of package {0}: ", counter);
userinput2 = Console.ReadLine();
result = (double.Parse(userinput2) * 2.35) + result;
counter++;
}
You should not have a problem with this as you've already declared result
above as 0
Upvotes: 1
Reputation: 644
Ah! Took me a sec to figure out the problem because it was so small! you need to change result = double.Parse(userinput2) * 2.35;
to result += double.Parse(userinput2) * 2.35;
Upvotes: 2