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

为什么前面一定要先赋值?
using   System;
using   System.Collections.Generic;
using   System.Text;

namespace   Interest
{
        class   Program
        {
                static   void   Main(string[]   args)
                {
                        decimal   amount,   principal   =   (decimal)1000.00;
                        double   rate   =   0.05;
                        string   output;
                        amount   =   1;
                        output   =   "Year\tAmount   on   deposit\n ";
                        for   (int   year   =   1;   year   <=   10;   year++)
                        {
                                amount   =   principal   *   (decimal)Math.Pow(1.0+rate,year);
                                output   +=   year   +   "\t "   +   string.Format( "{0:C} ",   amount)   +   "\n ";                      
                        }
                        Console.Write(output);
                        //   Console.Write(amount);//如果前面没有那个amount   =   1;就出错
                        Console.ReadLine();
                }
        }
}

如果前面没有那个amount   =   1;就出错,为什么?

请教!



------解决方案--------------------
amount为null时肯定会出错了...
可以初始值 设为0

------解决方案--------------------
用我们伟大的C语言导师的语录来说,就是:变量要先赋值,后使用。
------解决方案--------------------
你要知道C#是一种强类型的语言,而且要求所有的变量都必须首先赋值才能使用。amount因为是一个值类型,所以其初始值就是default(decimal)(不是空引用)。所以即使你没有amount=1;这句话,理论上在运行时是不会产生错误的。如果没有amount=1,则你说的错误一定是编辑阶段的错误!也就是说,编译过程可以检查是否使用了没有复制的变量。
------解决方案--------------------
你只需要记住C#中不允许使用没有初始化的变量。这种强制性的要求,可以降低代码编写错误,以及方便排除错误。也容易让别人查阅你的代码时,容易知道某个变量的值。