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).