### 新手想了很久了都不会做，求解 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);
} ``123456789`` ``````#include using namespace std; int main() { int n; cout << "Enter n: "; cin >> n; cout << "Sum = " << ( n % 2 ? (n+1)*(n+1)/2 : -n*(n/2+1) ) << '\n'; }``````

 ```Enter n: 100 Sum = -5100```

 ```Enter n: 101 Sum = 5202```

Or even:
 ``123456789`` ``````#include using namespace std; int main() { int n; cout << "Enter n: "; cin >> n; cout << "Sum = " << (2*(n%2)-1) * ((n*n+1)/2+n) << '\n'; }``````
Last edited on 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
 ``12345678910`` ``````#include #include 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.

edit: Fix line numbers
Last edited on
Topic archived. No new replies allowed.