新手想了很久了都不会做,求解

编写程序,计算下列公式中的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);
}
1
2
3
4
5
6
7
8
9
#include <iostream>
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:
1
2
3
4
5
6
7
8
9
#include <iostream>
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
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.


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