简体   繁体   中英

Variable doesn't exist in current context in for loop

This is probably something painfully obvious and will probably treat me to a portion of down-votes but... Visual Studio tells me that int i doesn't exist in the current context in the if/else statement . What is going on here?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LongSequence
{
    class Program
    {
        static void Main()
        {
            int numberToPrint;

            for (int i = 2; i <= 1000; i++);
            {  
                if (i % 2 == 0)

                    numberToPrint = i;
                else 
                    numberToPrint = i *(-1);
                Console.WriteLine(numberToPrint);  
            }
        }
    }
}
for (int i = 2; i <= 1000; i++);

This loop doesn't have body because of the ; . So it's not doing anything at all. So, your other code is treated as another statement,which is outside the scope of the loop, in which the variable i is created.

For loop should not have a termination, In your code, it will give an error because it terminates there.So value of i is not defined after that, Change it like below

for (int i = 2; i <= 1000; i++)
    {
     if (i % 2 == 0)
         numberToPrint = i;
     else 
         numberToPrint = i *(-1);
         Console.WriteLine(numberToPrint);
     }

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