c++ - While循环比较大小而不是数量
问题描述
我正在尝试创建一个while循环,该循环采用用户想要的“x”数量的整数(total
),然后继续循环直到用户输入所有整数。当用户输入 时total
,while 循环有一个比较,但它不起作用(我知道这一点,但我不知道如何解决它)。如果total
大于numbers
,则退出循环。我希望它循环直到输入选择的整数(由用户)!
#include <iostream>
#include <string>
#include <vector>
#include <numeric> //for accumulate
int sumUpTo(const std::vector<int>& vec, const std::size_t total) //const prevents parameters to not be modified in function.
{
if (total > vec.size())
return std::accumulate(vec.begin(), vec.end(), 0);
return std::accumulate(vec.begin(), vec.begin() + total, 0);
}
int main() {
std::vector <int> storage;
int total = 0, numbers = 0;
std::cout << "Please enter the amount of numbers you want to input\n";
std::cin >> total;
std::cout << "Now enter your numbers\n";
std::cin >> numbers;
while (numbers < total) {
std::cin >> numbers;
storage.push_back(numbers); //takes user input (numbers) and pushes them into the vector (storage).
}
sumUpTo(storage, total);
return 0;
}
解决方案
正如@Quimby 建议的那样,使用 for 循环。另外,您std::cin
为第一个号码打了两次电话,所以我已将其删除。在评论中,我添加了“while-loop”解决方案。
#include <iostream>
#include <string>
#include <vector>
#include <numeric> //for accumulate
int sumUpTo(const std::vector<int>& vec, const std::size_t total) //const prevents parameters to not be modified in function.
{
if (total > vec.size())
return std::accumulate(vec.begin(), vec.end(), 0);
return std::accumulate(vec.begin(), vec.begin() + total, 0);
}
int main() {
std::vector <int> storage;
int total = 0, numbers = 0;
std::cout << "Please enter the amount of numbers you want to input\n";
std::cin >> total;
std::cout << "Now enter your numbers\n";
for(int i = 0; i < total; i++)
{
std::cin >> numbers;
storage.push_back(numbers); //takes user input (numbers) and pushes them into the vector (storage).
}
//while (total > storage.size())
//{
// std::cin >> numbers;
// storage.push_back(numbers); //takes user input (numbers) and pushes them
//into
//the vector (storage).
//}
auto sum = sumUpTo(storage, total);
std::cout << sum << std::endl;
return 0;
}
推荐阅读
- sql - SQL 计数月平均值和 YTD 平均值
- ruby-on-rails - 登录/注册功能不工作,@current_user 不工作,会话不工作
- markdown - 在降价中调整 gif (github)
- dart - 如何使用 Angel/Jael 将函数附加到 onClick 事件?
- javascript - 如何在文件之间读取/写入 JSON 数据?(Node.Js)
- ios - 如何将路线坐标数组划分为等距离部分?
- reactjs - 使用 React.lazy 给出的元素类型无效
- java - 如何将多个服务放在一个类中,该类在 Activiti 中实现 JavaDelegate 接口
- python - sys.argv[0] 总是什么都不返回
- c - 依次出现 fwrite 和 fread 问题