我刚刚开始学习c#,遇到的一个问题,大家看看,现在要求计算1加到100的值,我刚开始的代码是这样的
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace @while
{
class Program
{
static void Main(string[] args)
{
int i = 1,t;
while (i < 101)
{
t+= i;
i++;
}
Console.WriteLine(t);
Console.ReadKey();
}
}
}
结果提示“错误 2 使用了未赋值的局部变量“t””
我把程序中刚刚开始定义的t赋值0后,就可以解决了,这是为什么啊,c语音里好像这样做的效果都是一样的啊,高手解释下啊~
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace @while
{
class Program
{
static void Main(string[] args)
{
int i = 1,t;
while (i < 101)
{
t+= i;
i++;
}
Console.WriteLine(t);
Console.ReadKey();
}
}
}
结果提示“错误 2 使用了未赋值的局部变量“t””
我把程序中刚刚开始定义的t赋值0后,就可以解决了,这是为什么啊,c语音里好像这样做的效果都是一样的啊,高手解释下啊~
for (int i = 1; i <= 100; i++)
sum += 100;
Console.WriteLine(sum);
=>
int i = 1, t = 0;
而int,string等都是类的别名.所以在使用它们的时候必须实例化.否则必然出错.
C#里面没有默认值,任何变量使用前都必须初始化。
Int别名是System.Int32 他允许的范围是从负数到最大整数