使用 c++ 对输入中的 3 个整数求和
为什么累积总是返回 0
这个答案使用push_back(),不需要知道输入了多少整数,因为向量会自动展开;通过这种方式,它回避了使您的代码失效的 std::vector 问题。
考虑一下,因为“多少 int”可能被提交很少是固定的,您更有可能想要“即时”计算有多少输入。所以也许使用一个循环,cin 到一个本地 var,然后 x.push_back(a_local_var),并重复直到某些条件(可能是 eof(),或本地 var == -1 等)x.size() 是你的计数器.
这是一个功能示例,使用命令行 vars 和 eof()(以及向量和累积)。
// Note: compile with -std=c++17 for the using comma list
#include <iostream>
using std::cout, std::cerr, std::endl, std::hex, std::dec, std::cin, std::flush; // c++17
#include <vector>
using std::vector;
#include <string>
using std::string;
#include <sstream>
using std::stringstream;
#include <numeric>
using std::accumulate;
#include <cassert>
class T951_t // ctor and dtor compiler provided defaults
{
public:
int operator()(int argc, char* argv[]) { return exec(argc, argv); } // functor entry
private:
stringstream ssIn; // to simulate user input
int exec(int argc, char* argv[])
{
int retVal = initTest(argc, argv); // transfer command line strings into ssIn
if(retVal != 0) return retVal;
// ------------------------------------------------------------
// simulate unknown quantity of ints
vector<int> x;
do {
int localInt = 0;
ssIn >> localInt;
if(!ssIn.good()) // was transfer ok?
{ // no
if (ssIn.eof()) break; // but we tolerate eof
// else err and exit
cerr << "\n !ssIn.good() failure after int value "
<< x.back() << endl;
assert(0); // harsh - user typo stops test
}
x.push_back(localInt); // yes transfer is ok, put int into vector
//cout << "\n " << localInt; // diagnostic
} while(true);
showResults(x);
return 0;
}
// this test uses a stringstream (ssIn) to deliver input to the app
// ssIn is initialized from the command line arguments
int initTest(int argc, char* argv[])
{
if (argc < 2) {
cerr << "\n integer input required" << endl;
return -1;
}
// test init
for (int i=1; i < argc; ++i) {
// cout << "\n " << argv[i]; // diagnostic
ssIn << argv[i] << " "; // user text into stream
}
cout << endl;
return 0;
}
// display size and contents of vector x
void showResults(vector<int> x)
{
cout << "\n x.size(): " << x.size() << endl;
int sum = std::accumulate(x.begin(), x.end(), 0);
for (auto i : x)
cout << " " << i;
cout << endl;
cout << "\n sums to: " << sum << '\n' << endl;
}
}; // class T951_t
int main(int argc, char* argv[]) { return T951_t()(argc, argv); } // call functor
测试:
./dumy951 1 2 3 55 12345678900
./dumy951 1 2 3 y 55 12345678900
./dumy951 1 2 3 4 5 6 7 8 9 10