首页 > 解决方案 > 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;
}

标签: c++while-loopc++-standard-library

解决方案


正如@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;
}

推荐阅读