【问题标题】:Vector Loop not functioning properly矢量循环无法正常工作
【发布时间】:2013-12-20 03:40:33
【问题描述】:

我正在尝试编写一个程序,该程序需要 10 个吃煎饼的人,并返回吃煎饼最多的人,我正在使用向量以便在用户输入时创建新元素并稍后返回,我尝试使用数组,但我遇到了困难。

#include <iostream>
#include <vector>
using namespace std ; 

int main()
{
    int  lnum , input ;
    int temp = 0;
    vector <int> persons(10) ;

    cout << "This program takes input for 10 people who ate pancakes, \
        then checks who   ate the most pancakes " << endl;

    cout << "Enter the amount of pancakes each person ate: " << endl ;
    cout << "Person 1: " ; 
    cin >> input ;
    persons.push_back(input);
    cout << "Person 2: " ; 
    cin >> input ;
    persons.push_back(input);
    cout << "Person 3: " ; 
    cin >> input ;
    persons.push_back(input);
    cout << "Person 4: " ; 
    cin >> input ;
    persons.push_back(input);
    cout << "Person 5: " ; 
    cin >> input ;
    persons.push_back(input);
    cout << "Person 6: " ; 
    cin >> input ;
    persons.push_back(input);
    cout << "Person 7: " ; 
    cin >> input ;
    persons.push_back(input);
    cout << "Person 8: " ; 
    cin >> input ;
    persons.push_back(input);
    cout << "Person 9: " ; 
    cin >> input ;
    persons.push_back(input);
    cout << "Person 10: " ; 
    cin >> input ;
    persons.push_back(input);
    cout << endl ;

    for(int i = 0 ; i < 11; i++){
        if(persons.at(i) > temp){
            temp == persons.at(i) ; 
        }
    }

    cout << temp << endl ;
    return 0 ;
}

几乎一切都运行良好,除了当我运行程序时,它返回 temp 为 0,而不是实际数字应该是什么。另外,当我调用像

这样的命令时
person.at(1) ;

它返回不正确的值,我做错了什么,这是逻辑错误还是语法?

【问题讨论】:

    标签: c++ arrays loops for-loop vector


    【解决方案1】:

    您可以替换整个部分:

    for(int i = 0; i < persons.size(); i++) // note the non-hard-coded conditional
    {
        if(persons.at(i) > temp)
        {
            temp = persons.at(i); // note fixed to assignment! 
        }
    }
    

    temp = std::max_element(persons.begin(), persons.end());
    

    【讨论】:

    • 谢谢,我知道可能有一种简单的方法可以找到最大的数字,但我仍然想使用手动方法来获得更好的结果。非常感谢。 :)
    【解决方案2】:

    首先,您的向量初始化不正确:

    vector <int> persons; // Vector will resize automatically
    

    然后,尝试= 而不是==,并更改循环的限制:

    for(int i = 0 ; i < persons.size(); i++){
        if(persons.at(i) > temp){
            temp = persons.at(i); // Assignment, not comparison
        }
    }
    

    请参阅@ZacHowland 的答案,以更轻松地找到vector 的最大元素。

    【讨论】:

    • 由于某种原因返回 0。
    • @BryanFajardo 已更新。
    • 当我这样初始化向量时,程序崩溃了。 ://
    • @BryanFajardo 那是因为你的 for 循环的限制不正确。
    【解决方案3】:

    这一行:

    temp == persons.at(i) ;
    

    不将 person[i] 的值赋给 temp。它比较两个值,然后删除布尔结果。

    您可能指的是单个=

    【讨论】:

    • 试过了,我实际上是先尝试过的,然后切换它看看是否可能是问题所在。两者都不起作用。
    猜你喜欢
    • 2019-01-01
    • 1970-01-01
    • 2014-12-02
    • 2013-08-09
    • 2013-10-30
    • 2013-10-19
    相关资源
    最近更新 更多