日期:2014-05-19  浏览次数:20843 次

为什么无法执行?新手刚学,谢谢!
string   comparison;
                        Console.WriteLine( "Enter   a   number: ");
                        double   var1   =   Convert.ToDouble(Console.ReadLine());
                        Console.WriteLine( "Enter   another   number: ");
                        double   var2   =   Convert.ToDouble(Console.ReadLine());
                          if   (var1   <   var2)
                                comparison   =   "less   than ";
                        if   (var1   ==   var2)
                                comparison   =   "equal   to ";
                        if   (var1   >   var2)
                                comparison   =   "greater   than ";
                            Console.WriteLine( "The   first   number   is   {0}   the   second           number. ",   comparison);//怎么能有错误呢?提示说Use   of   unassigned   local   variable   'comparison '
                        Console.ReadKey();

------解决方案--------------------
它不知道前面3个if已经包括了所有可能,认为还存在没有给comparison赋值的可能,因此报错
可以事先先给comparison赋一个 " "
string comparison= " ";
或者改一下判断
if (var1 < var2)
comparison = "less than ";
else if (var1 == var2)
comparison = "equal to ";
else
comparison = "greater than ";
------解决方案--------------------
local变量要先赋值再使用

string comparison = string.Empty;//-------> 这里改成这样
Console.WriteLine( "Enter a number: ");
double var1 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine( "Enter another number: ");
double var2 = Convert.ToDouble(Console.ReadLine());
if (var1 < var2)
comparison = "less than ";
if (var1 == var2)
comparison = "equal to ";
if (var1 > var2)
comparison = "greater than ";
Console.WriteLine( "The first number is {0} the second number. ", comparison);
Console.ReadKey();

------解决方案--------------------
string comparison; -> string comparison= " ";

编译器会检查变量使用时是否有初始值,否则编译通不过.
好象回答了一个远古问题...
------解决方案--------------------