简体   繁体   中英

Declaring a variable in a loop and using it outside?

I'm very new to c# and am trying to run this bit of code. I'm trying to make it so the question "How many miles were you able to travel in week {number}?" is repeated 4 times and this: int totalaverage = Convert.ToInt32(Console.ReadLine()); is repeated 4 times and each time added up. Then I need to use it outside the loop to make the finalaverage. Is there any way to do this?

    using System;

    namespace HelloWorld
    {
    class Program
    {
        static void Main()
        {
            Console.WriteLine("Whats your name?");
            string input = Console.ReadLine();
            Console.WriteLine($"Hi {input}");

            Console.WriteLine("What were you hoping to hit for your average?");
            int average = Convert.ToInt32(Console.ReadLine());

            int number = 1;

            while (number < 5)
            {
                Console.WriteLine($"How many miles were you able to travel in week {number}?");
                int totalaverage = Convert.ToInt32(Console.ReadLine());
 

                number = number + 1;
            }

            int finalaverage = totalaverage / 4;
            Console.WriteLine($"{input} you have averaged {finalaverage} miles per week");
            if (finalaverage >= average)
            {
                Console.WriteLine("Congratulations you have met your target");
            }
            else
            {
                Console.WriteLine("Sorry you have not met your target");
            }
        }
    }
}

You need to declare your variable outside of your loop, in order to use it outside of your loop, something like this:

int number = 1;
int totalaverage = 0;

    while (number < 5)
    {
        Console.WriteLine($"How many miles were you able to travel in week {number}?");
        totalaverage = Convert.ToInt32(Console.ReadLine());
        number = number + 1;
    }

    int finalaverage = totalaverage / 4;
    Console.WriteLine($"{input} you have averaged {finalaverage} miles per week");
    if (finalaverage >= average)
    {
        Console.WriteLine("Congratulations you have met your target");
    }
    else
    {
        Console.WriteLine("Sorry you have not met your target");
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM