c# console application unassigned local variable [duplicate]

霸气de小男生 提交于 2019-12-13 09:18:21

问题


        int ValueOne, ValueTwo, Numchar, Total;
    Console.WriteLine("This Is A Program For doing any Of the four mathematical Proccesses");
    Console.WriteLine("You can Add , substract , Divide And Multiply");
    Console.WriteLine("When Asked Please Type The Values Or The Proccesses You Want.");
    Console.WriteLine("Please Type The First Value");
    ValueOne = Convert.ToInt32((Console.ReadLine()));
    Console.WriteLine("Please Type The Second Value");
    ValueTwo = Convert.ToInt32((Console.ReadLine()));
    Console.WriteLine("Please Enter The Number Of The Proccess/Character You Want Meaning That (1 = +) , (2 = -) , (3 = *) , (4 = /)");
    Numchar = Convert.ToInt32((Console.ReadLine()));
    if (Numchar == 1)
        Total = ValueOne + ValueTwo;
    if (Numchar == 2)
        Total = ValueOne + ValueTwo;
    if (Numchar == 3)
        Total = ValueOne * ValueTwo;
    if (Numchar == 4)
        Total = ValueOne / ValueTwo;
    Console.WriteLine("The Total Is :");
    Console.WriteLine(Total);
    Console.ReadLine();

the Console.WriteLine(Total); at the end is apparently an unassigned local variable , though it should be assigned from the Lines beneath the "If" lines, also note that I'm new in visual studio and i just started taking The Courses , also , i don't think this is a duplicate because the other post's fix Didn't Work for me.


回答1:


Let's say that your code didn't produce an error, and compiled and ran. What do you think would happen if NumChar wasn't 1, 2, 3, or 4?

Your code would never reach any of the statements in your ifs there, and would never assign an initial value to Total. Since this is entirely possible given your program (and would be impossible to check for in general -- see the Halting Problem), the error is substantiated and necessary.



来源:https://stackoverflow.com/questions/31280102/c-sharp-console-application-unassigned-local-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!