在C++中添加整数的输出
Add Output of Integers in C++?
我正在研究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
}
实现这一点的典型方法是使用另一个变量来保存总和。您逐渐将每个数字添加到这个变量中,直到您必须在循环结束时求和。
相关文章:
- 在数组中输入 n 个整数的列表,并以类似于钟摆来回移动的方式排列它们. 输入-1 3 2 5 4,输出5 3 1 2 4
- 为对象分配整数.输出将是什么?
- 在 c++ 中输出 64 位整数
- Vscode/C++ - cout 无法输出完整的句子,也无法与整数连接
- 为什么输出是整数而不是双精度?
- 如果我们在其中输入一个整数,则字符会给出整数作为输出,但是当分配给它一个整数时,这不会发生。为什么?
- C++ 读取未知数量的整数到 cin 并输出总和
- libmpg123 在我使用整数编码读取 mp3 时强制浮点输出
- 我需要编写一个程序来读取一个文件,该文件将输出所有唯一的整数,如果已经看到整数,它将被关闭
- 按升序输出整数时,将最后一个整数放在新行上
- 如何包含整数之间的空格作为输出
- 编写一个程序,提示用户输入一个整数,然后输出数字的单个数字和数字的总和
- 输出显示多个带整数的字符串值
- 为什么从输入中收集字符串时整数输出为0
- 在控制台上输出我从文件中读取的整数,将程序插入无限循环
- 使用递归函数 (c++) 将长字符串转换为整数时输出错误
- 输出可序列化的排序整数
- 函数,以 C++ 为单位输出整数的位数之和
- c++程序输出整数时异常退出
- 操作符重载- c++ toString输出整数