如何使用C for循环编写一个系列?

时间:2017-09-28 12:38:16

标签: c

我在为一个系列编写代码时遇到了麻烦,我相信这与我的if语句有关,但我很难过。这个系列应该是

((-1)^(n+1))*n^2

但我一直得到错误的输出。这是我的代码:

{{1}}

3 个答案:

答案 0 :(得分:0)

我不知道我是否理解正确,它应该是这样的?:

#include <stdio.h>

int main() {   
    int n,t=1,firstPart,sum=0,i;

    printf("Enter an integer number:");
    scanf("%d",&n);
    printf("The serie is: \n");

    for(i=1;i<=n;i++) {
        if (i%2 == 0) {
            firstPart = 1;
        }
        else {
            firstPart = -1;
        }

        t=firstPart*(i*i);
        printf(" %d\t ", t);
        sum=sum+t;
    }

    printf("\nThe value of the series is: %d\n",sum);
    return (0);
}

对于n = 4,系列是:

-1 / 4 / -9 / 16 /

,总和为10

答案 1 :(得分:0)

您必须检查i+1而不是i,并将t*t替换为i*i。您不需要任何额外的变量,例如t

#include <stdio.h>

int main()
{
    int n,nextTerm,sum=0,i;
    printf("Enter an integer number:");
    scanf("%d",&n);
    for(i=1;i<=n;i++) {
        if ((i+1)%2 == 0) 
           nextTerm = 1;
        else
           nextTerm = -1;
        sum=sum+(nextTerm*i*i);
    }
    printf("The value of the series is: %d\n",sum);
    return 0;
}

系列是这样的:

1, -4, 9, -16, ...

<强>输出:

Enter an integer number:4

The value of the series is: -10

答案 2 :(得分:-1)

(t*t)替换为(i*i)

#include <stdio.h>

int main() {
    int n,i,sum=0,nextTerm,t;
    printf("Enter an integer number:");
    scanf("%d",&n);
    for(i=1;i<=n;i++) {
        if (t%2 == 0) {
            nextTerm = 1;
        }
        else {
            nextTerm = -1;
        }
        t=nextTerm*(i*i);
        sum=sum+t;
    }
    printf("The value of the series is: %d\n",sum);
    return (0);
}

输出 -

Enter an integer number:4

The value of the series is: -10