简体   繁体   English

用C ++计算总和

[英]Calculating the sum in C++

How do I calculate the sum to below in C++? 在C ++中,如何计算总和? I tried the following code but failed. 我尝试了以下代码,但失败了。

在此处输入图片说明

#include <iostream>
using namespace std;
int main()
{
    int n, p, r = -1;
    cin >> n;
    for (p = 0; p < 10; p++)
        r *= (-1);
    cout << r << endl;
    return 0;
}
#include <iostream>
using namespace std;
int main()
{
    int p, r = 1;
    int iSum=0;
    // cin >> n;

    for (p = 0; p <= 10; p++)
    {
        r *= (-1);
        iSum+=r;
    }
    cout << iSum << endl;
    return 0;
}

That's basic mathematics, there is no need for a loop, you can just calculate -1 * (upperLimit + 1)%2 . 这是基本的数学,不需要循环,您只需计算-1 * (upperLimit + 1)%2

Look at the series and think: -1 +1 -1 +1 -1 +1 ... . 查看该系列并思考: -1 +1 -1 +1 -1 +1 ...

Although @Flavius is right, the sum starts from 0 so it'll be -1 * (upperLimit+1)%2 as the sum iterates not 10 but 11 times. 尽管@Flavius是正确的,但是总和从0开始,所以它将是-1 * (upperLimit+1)%2因为总和不是迭代10次而是11次。 The upperLimit%2 thing works for sums starting at 1 upperLimit%2对于从1开始的总和有效

PS: Sorry for answering, I cannot yet comment, just registered. PS:很抱歉回答,我还没有评论,只是注册了。

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

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