在C++中添加整数的输出

Add Output of Integers in C++?

本文关键字:输出 整数 添加 C++      更新时间:2023-10-16

我正在研究Project Euler,这是第一个问题,我已经用这个程序输出了我需要的数字,但我不知道如何将输出的数字相加。

这是代码:

#include <iostream>
#include <cmath>
int main(void) {
    int test = 0;
    while (test<1000) {
        test++;
            if (test%3 == 0 && test%5 == 0) {
                std::cout << test << std::endl;
            }
    }
    std::cin.get();
    return 0;
}

最简单的选项是添加一个total变量作为条件匹配。

第一步是创建它并将其初始化为0,这样以后就可以得到正确的数字。

int total = 0;

然后,将小计添加到其中,从而累积总的总和。

total += 5;
...
total += 2;
//the two subtotals result in total being 7; no intermediate printing needed

一旦你添加了小计,你就可以把它作为总的总数打印出来。

std::cout << total;

现在,以下是它如何适应手头的代码,以及其他一些指针:

#include <iostream>
#include <cmath> //<-- you're not using anything in here, so get rid of it
int main() {
    int test = 0;
    int total = 0; //step 1; don't forget to initialize it to 0
    while (test<1000) { //consider a for loop instead
        test++;
        if (test % 3 == 0 && test % 5 == 0) {
            //std::cout << test << std::endl;
            total += test; //step 2; replace above with this to add subtotals
        }
    }
    std::cout << total << std::endl; //step 3; now we just output the grand total
    std::cin.get();    
    return 0; //this is implicit in c++ if not provided
}

实现这一点的典型方法是使用另一个变量来保存总和。您逐渐将每个数字添加到这个变量中,直到您必须在循环结束时求和。