编写程序,计算下列公式中的s
s=1*2-2*3+3*4-4*5+...+(-1)^(n-1)*n*(n+1)
这是自己做的,实在不会了
#include<stdio.h>
#include<math.h>
int main()
{
float n, result = 0;
printf("%d", &n);
result = pow(-1, n - 1);
result *= n*(n + 1);
printf("%d", result);
}
Google translate:
Title: The novice has been thinking about it for a long time and can't do it, solve it
Write a new program to calculate s in the following formula
s=1*2-2*3+3*4-4*5+...+(-1)^(n-1)*n*(n+1)
I did it myself, not anymore
1 2 3 4 5 6 7 8 9 10
#include<stdio.h>
#include<math.h>
int main()
{
float n, result = 0;
printf("%d", &n);
result = pow(-1, n - 1);
result *= n*(n + 1);
printf("%d", result);
}
Line 5: n is uninitialized variable.
Line 6: &n is going to return the address of n. %d is the wrong format specifier for printing an address. Should be %p.
Line 7,8: n is uninitialized variable. Garbage in. Garbage out.
Line 9: result is a float. %d is the wrong format specifier for a float. Should be %f.