简体   繁体   中英

Why aren't my if statements inside the for loops working properly?

I'm trying to do a w3resource.com exercise and my if statements inside the for loops aren't being respected(the code inside the if statement is running even if the condition isn't true). Please help me

I've already tried to replace the for loops with while loops and the problem persisted. I've tried to see what's wrong with my if statements but I couldn't find anything.

#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;
}

The program is not working properly, outputting the wrong numbers.

In the second and third loop you put semicolon after the if :

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

so effectively the condition has empty block and the block with your code is always executed. It is more visible like this:

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

{        // always executed
    <your code>
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM