C# 在 if 循环中使用未赋值的局部变量

问题描述:

因为我是一个该死的初学者,所以我需要一些帮助:

since I'm a bloody beginner, I'll need some help here:

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

namespace Gauss_Algorithmus
{
    class Program
    {
        static void Main(string[] args)
        {
            if (x1 > 0 && x2 > 0)
            {
                 x02 = (x2 * x1) - (x1 * x2); 
                 y02 = (y2 * x1) - (x1 * y2);
                 z02 = (z2 * x1) - (x1 * z2);
                 d02 = (d2 * x1) - (x1 * d2);
            }
            Console.WriteLine("2.:   " + x02 + "x + " + y02 + "y + " + z02 + "  d02);
       }
   }

它说:

使用未赋值的局部变量x01,等等......

Use of unassigned local variable "x01, etc....

我理解错误并知道 x01 只是在本地范围内定义,但不知道如何修复它,因为 x01 等需要在 if 循环内定义.

I understand the error and know that x01 is just defined in a local scope, but don't know how to fix it since x01, etc. needs to be defined inside the if loop.

我希望你们能帮助我,在此先感谢..

I hope you can help me out guys, thanks in advance..

最好的建议是做一个 C# 入门教程.

The best advise is to do a getting started with C# tutorial.

具体回答你的问题有两处错误:

Specifically answering your question there are two things wrong:

  1. 您需要声明变量.基本上使用 var x02 = (x2 * x1) - (x1 * x2); etc
  2. 变量的使用需要在同一范围内.您必须将 Console.WriteLine 移动到 if 块内,或者您需要像这样在 if 块之前声明和初始化变量:var x02 = 0; etc
  1. You need to declare the variables. Basically using var x02 = (x2 * x1) - (x1 * x2); etc
  2. The usage of the variables needs to be in the same scope. Either you have to move the Console.WriteLine inside the if block or you need to declare and initialize the variables before the if block like this: var x02 = 0; etc