【发布时间】:2020-08-08 17:18:33
【问题描述】:
我正在尝试打印出向量中第一个“x”元素的总和。基本上,用户输入一堆数字(这些数字被推回向量中),一旦他们决定退出循环,他们就必须选择他们想要求和的元素数量。
例如,如果他们输入“6, 5, 43, 21, 2, 1”,他们会选择想要求和的数字,例如“3”。最后输出应该是“前3个数字的和是”6,5,43是54”。
我发现的唯一一件事是找到(我相信)对我没有多大用处的向量的总和。
我还使用<vector> 库检查了一个 c++ 网站,但无法确定是否有任何功能很有用。这是针对 c++ 的,请记住,我是一名新程序员。
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
// 1) read in numbers from user input, into vector -DONE
// 2) Include a prompt for user to choose to stop inputting numbers - DONE
// 3) ask user how many nums they want to sum from vector -
// 4) print the sum of the first (e.g. 3 if user chooses) elemens in vector.
vector <int> nums;
int userInput, n, total;
cout << "Please enter some numbers (press '|' to stop input) " << endl;
while (cin >> userInput)
{
if (userInput == '|')
{
break; //stops the loop if the input is |.
}
nums.push_back(userInput); //push back userInput into nums vector.
}
cout << "How many numbers do you want to sum from the vector (the numbers you inputted) ? " << endl;
cin >> total;
cout << nums.size() - nums[total]; //stuck here
return 0;
}
【问题讨论】:
-
if (userInput == '|')真的有效吗?您确定您正在阅读所有值吗?如果用户想要输入|的整数版本会发生什么? -
尝试输入
124,如果您的系统使用 Shift_JIS 或 UTF-8(或其他 ASCII 兼容字符代码),它将停止读取输入。 -
我还检查了一个带有 "
库的 c++ 网站,但无法确定是否有任何功能很有用 -- 您检查了错误的类别。您应该检查的函数类别是使用值容器的 STL 算法和数值函数。在这种情况下,您将寻找std::accumulate(下面已经给出答案)。 -
@cigien 我用它测试了程序,循环接受用户输入,直到 |被按下,所以它确实有效(尽管我可能以一种糟糕的方式编写了代码)
-
@MikeCAT 谢谢,我知道这一点。但是,我正在进行的练习告诉我使用“int”数据类型,所以我想我暂时坚持使用它。
标签: c++ algorithm sum stdvector c++-standard-library