最简单的选项是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
}