简体   繁体   English

C#变量已使用但从未分配

[英]C# variable used but never assigned

So I have been working on a program that calculates nearest and larger 3rd power to a number which is entered (if entered number is 20 then result is 27 because 3^3=27). 因此,我一直在研究一个程序,该程序计算与输入的数字最接近且更大的三次方(如果输入的数字为20,则结果为27,因为3 ^ 3 = 27)。 However due to my lack of skills I have stumbled upon a problem. 但是由于我缺乏技能,我偶然发现了一个问题。 It seems that variable result is used but never assigned (even if its value is asigned to it in a for cycle) Here is the code: 似乎使用了变量result但从未分配过(即使它的值在for周期中已分配给它),下面是代码:

namespace ConsoleApp6
{
class Program
{
    static void Main(string[] args)
    {
        Console.Write("Enter a number: ");
        int num = Convert.ToInt32(Console.ReadLine());
        int result;
        for(int i = num; (i * i * i) >= 0; i--)
        {
            result = i * i * i;
        }
        Console.WriteLine("Nest 3rd pow. is: " + result);
        Console.WriteLine("Press any key to contiunue...");
        Console.ReadLine();
    }
 }
}

Thank you for your answers. 谢谢您的回答。

The comments have probably dealt with your issue (you didn't set a value for result when you created it, the compiler can foresee a scenario where no loop runs and there is never any assignment, but you always use it. A "use of unassigned local variable" error arises), but I wanted to point out that your program is some way off solving the advertised problem of finding the next larger int cube than the entered number 这些注释可能处理了您的问题(创建时未设置result的值,编译器可以预见没有循环运行且永远没有任何赋值的情况,但是您总是使用它。未分配的局部变量”错误出现),但我想指出的是,您的程序离解决比找到的数字大一个下一个更大的int多维数据集的广告问题有一定距离

To solve this, cube root the entered number, round it up to the next integer and cube it 要解决此问题,请对输入的数字求根,将其四舍五入到下一个整数,然后对它求立方

Math.Pow(Math.Ceiling(Math.Pow(num, 1.0/3.0)), 3.0);

As things stand, I'm not really sure what you're aiming to achieve with the loop, and it looks like it will run however many times needed to set the result to 0 (it loops until i is zero, result is 0). 就目前情况而言,我不确定您要通过循环实现的目标,并且看起来它将运行很多次,但需要将结果设置为0(它循环直到i为零,结果为0)。 。 Perhaps you intended to start i from 2 and increment i until result was larger than num, but that seems less efficient than doing the calc directly 也许您打算将i从2开始并递增i直到结果大于num,但这似乎比直接执行calc效率低

One overall rule of good programming praxis is to initialize a variable on the declaration. 良好编程习惯的总体规则是在声明上初始化变量。

The compiler error says that you are using result when it has not been assigned. 编译器错误表明尚未分配result时,您正在使用result That's because in your for loop you can't predict that it will iterate at least one time (therefore there are scenarios where the variable is used without ever being assigned). 这是因为在您的for loop您无法预测它会重复至少一次(因此,在某些情况下,该变量在未分配的情况下使用)。

As have been mentioned before, this can be fixed by initializing the variable (0 is the standard) 如前所述,可以通过初始化变量来解决(标准为0)

int result = 0;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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