为什么for循环不起作用?当我输入值时

时间:2015-10-01 23:40:48

标签: c++ loops for-loop

这是代码。我不知道是什么问题。当我输入值时,for循环不起作用。 我正在研究一个问题,请问我: 找到几个整数中的两个最大值。假设第一个整数读取指定了剩余要输入的值的数量。谢谢你们!

#include <iostream>
using namespace std;
int main()
{
int i, largest, secondLargest, temp;
cout << "Enter the number of integers to be processed followed by the integers:";
cin >> i;
cin >> largest;
cin >> secondLargest;

if (secondLargest > largest)            
{
    temp = secondLargest;
    secondLargest = largest;
    largest = temp;
}
for (int b; i > 1; i--)
{
    cin >> b;
    if (b > largest)
    {
        secondLargest = largest;
        largest = b;
    }
}
cout << "Largest is " << largest << endl << "Second largest is " << secondLargest << endl;

system("pause");
}

3 个答案:

答案 0 :(得分:1)

程序和循环工作。至少差不多。

唯一的问题是,循环体执行(i-1)次而不是(i-2)次。

要解决此问题,您可以将i > 1更改为i > 2

编辑:

哦,如果b介于largestsecond_largest之间,您还必须检查。在这种情况下,您可以将second_largest替换为b

答案 1 :(得分:1)

将循环更改为

    for (int b; i > 2; i--)

原因是因为你已经在程序顶部要求前两个整数,所以你必须考虑到这一点。循环将从i开始,我只想说我想输入10个整数,将计数到3然后停止,因为你已经要求顶部的最大和第二个最大值:

Here's an example:
    cin >> i;
    cin >> largest
    cin >> secondLargest;

    For loop declared i = 10
    i = 9
    i = 8
    i = 7
    i = 6
    i = 5
    i = 4
    i = 3

Total integers asked for = 10

我希望这有帮助!问你是否有问题!

答案 2 :(得分:1)

#include <iostream>
using namespace std;
int main()
{
int i, largest, secondLargest, temp;
cout << "Enter the number of integers to be processed followed by the integers:";
cin >> i;
cin >> largest;
cin >> secondLargest;

if (secondLargest > largest)            
{
    temp = secondLargest;
    secondLargest = largest;
    largest = temp;
}
for (int b; i > 2; i--)
{
    cin >> b;

    if (b > largest)
    {
        secondLargest = largest;
        largest = b;
        b = 0;
    }
    if (b > secondLargest)
        secondLargest = b;
}
cout << "Largest is " << largest << endl << "Second largest is " << secondLargest << endl;

system("pause");

}