为什么我的for循环中的if语句不能正常工作?

时间:2019-05-28 12:54:37

标签: c++

我正在尝试执行w3resource.com练习,并且不尊重我的for循环中的if语句(即使条件不成立,if语句中的代码也正在运行)。请帮助我

我已经尝试用while循环替换for循环,问题仍然存在。我试图查看if语句出了什么问题,但是找不到任何东西。

#include <iostream>
#include <algorithm>
#include <iterator>

void findAndPrintThe3LargestElements(int array[], int arraySize)
{
    int largestNumbers[] = { array[0], array[0], array[0] };
    for (int nextIndexNumber = 1; nextIndexNumber < arraySize; ++nextIndexNumber)
    {
        if (array[nextIndexNumber] > largestNumbers[0])
            largestNumbers[0] = array[nextIndexNumber];
    }


    for (int nextIndexNumber = 1; nextIndexNumber < arraySize; ++nextIndexNumber)
    {
        if (array[nextIndexNumber] > largestNumbers[1] && array[nextIndexNumber] != largestNumbers[0]);
        {
            largestNumbers[1] = array[nextIndexNumber];
        }
    }

    for (int nextIndexNumber = 1; nextIndexNumber < arraySize; ++nextIndexNumber)
    {
        if (array[nextIndexNumber] > largestNumbers[2] && array[nextIndexNumber] != largestNumbers[0] &&
            array[nextIndexNumber] != largestNumbers[1]);
        {
            largestNumbers[2] = array[nextIndexNumber];
        }
    }

    std::cout << "The three largest numbers in the array are: " << largestNumbers[0] << ", " << largestNumbers[1]
        << ", " << largestNumbers[2] << ".";
}

int main()
{
    int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    int arraySize = std::size(array);
    findAndPrintThe3LargestElements(array, arraySize);
    return 0;
}

程序无法正常运行,输出了错误的数字。

1 个答案:

答案 0 :(得分:0)

在第二个和第三个循环中,将分号放在if之后:

if (<condidion>);
{
    <your code>
}

因此条件实际上具有空块,并且始终执行带有您的代码的块。像这样更可见:

if (<condition>)
    ;    // no operation here

{        // always executed
    <your code>
}