打印系列的总和最多n个数字 [英] Print the sum of the series upto n numbers

查看:63
本文介绍了打印系列的总和最多n个数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

1 - (2/3!)+(3/4!) - (4/5!)+ ....±(n /(n + 1)!)。



我的尝试:



#include< stdio.h>

#include< conio.h>

void main()

{

int i,sum = 0;

for(j = 0; j< = n; j ++)

{

sum + = 2i / i + 1;

}

printf(sum =%d,sum);

}

1 - (2/3!) + (3/4!) - (4/5!) + .... ± (n/(n+1)!).

What I have tried:

#include<stdio.h>
#include<conio.h>
void main()
{
int i,sum=0;
for(j=0;j<=n;j++)
{
sum+=2i/i+1;
}
printf("the sum=%d",sum);
}

推荐答案

你的for循环需求将i作为变量,因为你已声明它而不是j。



你没有问题要回答,但无论如何我会给出一些建议。首先,编写一个函数来计算值的阶乘。这将为系列中的每个值提供分母。其余部分将是一个简单的值划分,并将结果汇​​总到一个for循环中。



这里唯一的半难点是交替加法和减法。你可以用几种方法做到这一点。一种是使用乘数并将其从+1到-1交替。另一个是有一个布尔标志,从true到false交替显示,并告诉你是否应该添加或减去结果。还有一种方法是根据循环索引是奇数还是偶数来确定加法或减法。你可以找到以循环索引的模2为模型。
Your for loop needs to have i as its variable since you have declared it and not j.

You don't have a question to answer but I'll give some advice anyway. First, write a function to compute the factorial of a value. That will provide the denominator for each value in the series. The rest of this will be a simple division of values and summing the results inside a for loop.

The only semi-tricky thing here is the alternating addition and subtraction. You can do that several ways. One is to use a multiplier and alternate it from +1 to -1. Another is to have a boolean flag that alternates from true to false and tells you whether you should add or subtract the result. Yet another is to determine addition or subtraction based on whether to loop index is odd or even which you can find taking modulo 2 of the loop index.


我认为你应该这样做。



I think you should do similar like this.

#include<stdio.h>
#include<conio.h>
int fact(int n)
{
    if(n == 0)
    {
       return 1;
    }
    return n * fact(n-1);
}
void main()
{
    int sum = 1, delta = -1;
    for(int i=2; i<=n; ++i)
    {
       sum += ((i / fact(i + 1)) * delta);
       delta *= -1;
    }
    printf("the sum=%d",sum);
}





我没有编译上面的代码。但我认为这会对你有帮助。



I didn't compile the above code. But I think it would help you.


这篇关于打印系列的总和最多n个数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆