1

我在程序的开头声明了一个变量。我相信该变量是在程序范围内声明和使用的。

double a,u; int i;
for (i = 0; i < 30; i++)
{
    u += (i + 1) * datas[i];
}

我可以检查通过调试模式存储的 u 的值,但不能在其他地方使用它“使用未分配的局部变量 u”我应该使用十进制代替吗?我用十进制表示,但因为我也用过

datas[i-1] = Convert.ToDouble(dataReader["high"]);

在程序的其他地方,我认为 c# 中没有 Convert.toDecimal() ;双精度和十进制有什么区别。PS:我以前从未使用过十进制

4

5 回答 5

11

In C#, the use of uninitialized variables is not allowed. If you do not assign a default value, or use a constructor, the compiler won't know what your value is and therefore cannot use it.

You need to change double a for double a = 0; or double a = new double();. The new double() operation will set the default value to zero, according to this default value table. However, = 0 is the preferred syntax.

As a side note, declaring variables on their own line is also a good practice in C#. So is declaring the loop variable directly in the for statement. I'd also recommend using meaningful variable names (a and u are not obvious for everyone), readability is pretty important.

double a = 0;
double u = 0;

for (int i = 0; i < 30; i++)
{
    u += (i + 1) * datas[i];
}

what is the difference between double and decimal.

decimal is usually used for currency or financial operations because of its greater precision (28-29 digits, compared to 15-16 for double). However, it have a much much smaller range than double. decimal range goes up to 7.9 x 10^28, while double goes up to 1.7 x 10^308.

On the other hand, if you don't need great precision or great range, float would be the best type to use as it is 32-bit (compared to 64 for double).

于 2013-08-08T15:41:33.857 回答
9

变量 u 没有被赋值,因此不能在循环中使用。试试这个:

double a = 0;double u = 0; int i;
for (i = 0; i < 30; i++)
{
    u += (i + 1) * datas[i];
}
于 2013-08-08T15:32:51.193 回答
5

该变量u在第一次执行时没有赋值,u += ...
因为u += x;它相当于u = u + x;编译器将标记它。u确实有一个默认值,0但编译器不会让你使用它,它在这里强制执行良好的编程风格。

你可能想要的是:

double a, u = 0; 

for (int i = 0; i < datas.Length; i++)
{
    u += (i + 1) * datas[i];
}

不过,您仍然可能遇到同样的问题a

于 2013-08-08T15:32:22.897 回答
2

您需要先分配一个值,u然后才能使用它。

double u = 0;

编译器转换u += 1u = u + 1. 如您所见,您读取u了 ,但尚未为该变量赋值。这就是为什么编译器告诉您正在使用未分配的局部变量

于 2013-08-08T15:34:59.130 回答
0

您从未为变量 u 赋值。将您的声明更改为...

双 u = 0;

于 2013-08-08T15:33:29.120 回答