简体   繁体   English

求和一系列正负分数

[英]Sum a sequence of positive and negative fraction

I have a homework to make an algorithms for sum this sequence : S = 1 - 1/2 + 1/4 - 1/6 + 1/8 - 1/10 + ... + 1/2n if the user input 2 the sum will be 1 - 1/2 = 1/2 and etc. 我有一个功课来制作一个算法来求和这个序列: S = 1 - 1/2 + 1/4 - 1/6 + 1/8 - 1/10 + ... + 1/2n如果用户输入2总和将是1 - 1/2 = 1/2等。

Here is my coding : 这是我的编码:

int main() {

    int num, N, k;
    double S;
    cout << "enter the sequence : ";
    cin >> N;
    for (num = 1, k = 0, S = 1; num <=N; num++) {
        num++;
        k=+2;
        if (num % 2 == 0) {
            S -= 1/k;
        } else {
            S += 1/k;
        }
    }
    cout << "The sum is " << S;
    system("PAUSE");
    return 0;
}

I'm so confused why the sum always refer to 1 ?? 我很困惑为什么总和总是指1? Can anyone explain to me why this happen?? 任何人都可以向我解释为什么会这样吗?

Try 1./k — otherwise integer division of 1 by anything will yield zero. 尝试1./k - 否则任何东西的1的整数除法将产生零。 (and see the other answer about =+ vs += typo). (并查看关于=+ vs +=拼写错误的其他答案)。

In your loop you have this 在你的循环中你有这个

k=+2;

so you assign the value 2 to k every iteration. 所以你在每次迭代时都将值2分配给k You probably want 你可能想要

k+=2;

also take heed of the integer division problem highlighted in the other answer 还要注意另一个答案中突出显示的整数除法问题

for(num = 1, sum = 1; num <=N; num++){
    if(num%2==0){
        sum += 1/(num*2);
    }else{
        sum -= 1/(num*2);
    }
}

That should do it, provided the nth term in your sequence is (1/((n-1)*2)) . 如果序列中的第n个项是(1/((n-1)*2)) ,那应该这样做。

EDIT: As pointed out below, when performing division, one of the operands needs to be non integer to prevent the result from being an integer. 编辑:如下所述,在执行除法时,其中一个操作数需要是非整数,以防止结果为整数。 The correction to my attempt above would be: 对我上述尝试的更正将是:

for(num = 1, sum = 1; num <=N; num++){
    if(num%2==0){
        sum += 1.0/(num*2);
    }else{
        sum -= 1.0/(num*2);
    }
}

http://codepad.org/KgGAxKxS http://codepad.org/KgGAxKxS

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM