C程序计算1-2 + 3-4 + 5-6 + 7-8 ... N个项的和

The series is: 1-2+3-4+5-6+7-8...N terms, we have to find out the sum up to Nth terms.

该序列是: 1-2 + 3-4 + 5-6 + 7-8 ... N个项 ,我们必须找出第N个项之和。

Solution:

解:

Let's analyse this problem,

让我们分析这个问题,

    If we want Sum of this series up to 2nd term then sum will be:
        1-2 =-1
    Up to 3rd term:
        1-2+3 =2
    Up to 4th term 
        1-2+3-4 = -2
    Up to 5th term:
        1-2+3-4+5= 3
        .
        .
        .

Now we can conclude that if we want sum up to an Odd term then we always get sum as ((N+1)/2) and if we want sum up to an Even term the sum is in the form of (-1*(N/2)).

现在我们可以得出结论,如果要对一个奇数项求和,则总和为((N + 1)/ 2),如果要对一个偶数项求和,则总和为(-1 * (N / 2))。

Now Let's make logic for this using c programming,

现在,让我们使用C编程为此逻辑,

#include <stdio.h>

//function for creating the sum of the 
//series up to Nth term
int series_sum(int n)
{
    if (n % 2 == 0)
        return (-(n / 2));
    else
        return ((n + 1) / 2);
}

// main code
int main()
{
    int n;
    printf("Series:1-2+3-4+5-6+7-8.....N\n");
    printf("Want some up to N terms?\nEnter the N term:");
    scanf("%d", &n);
    
    printf("Sum is:%d", series_sum(n));
    
    return 0;
}

Output

输出量

Series:1-2+3-4+5-6+7-8.....N
Want some up to N terms?
Enter the N term:10
Sum is:-5

Read more...

阅读更多...

翻译自: https://www.includehelp.com/c-programs/calculate-the-sum-of-the-series-1-2-3-4-5-6-7-8-n-terms.aspx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值