求以下表达式的值:
1. 1 - 2 + 3 - 4 + … + m
public static int Foo1(int m)
{
int sum = 0;
for (int i = 1; i <= m; i++)
{
if (i % 2 == 0)
{
sum -= i;
}
else
{
sum += i;
}
}
return sum;
}
2. (1-2)+(3-4)+(5-6)... + m
public static int Foo2(int m)
{
int sum = 0;
if (m % 2 == 0)
{
sum = -(m / 2);
}
else
{
sum = -(m - 1) / 2 + m;
}
return sum;
}
3. 1 + (-2 + 3)+(-4 + 5)+(-6 + 7)... + m
public static int Foo3(int m)
{
int sum = 0;
if (m % 2 == 0)
{
sum = (m - 2) / 2 + 1 - m;
}
else
{
sum = (m - 1) / 2 + 1;
}
return sum;
}