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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With