简体   繁体   中英

finding the minimum of 2 numbers in an array in C++

#include <iostream>
using namespace std;
int main()
{
    int a[42] = {-16748, 1861305,
-1677019, 2959868,
8279642, -5614317,
-6959809, -8869681,
5841371, 684147,
9078506, -9854715,
5442553, -8007477,
5455657, 400271,
-8326571, -589876,
-2139466, 7869921,
9462518, 8289564,
-1158751, -1908990,
3315049, 5073796,
-2511851, 6631645,
960911, 5459324,
9951099, 7368220,
1403411, -6792887,
2886747, 4303636,
-4393903, -1918146,
-2402605, -1947543,
-6002778, -7925503,
};
    int b[21];
    for (int i=0; i<=42; i+=2)
    {
        int n=0;
        if (i == 0) {
            if (a[i] > a[i+1])
                b[i] = a[i+1];
            else if (a[i] < a[i+1])
                b[i] = a[i];
        } 
        else if (i > 0) {
            if (a[i] > a[i+1])
                b[i-n] = a[i+1];
            else if (a[i] < a[i+1]) {
                b[i-n] = a[i];
            }    
        }
        n++;
    }
    for (int i=0; i<=21; i++)
        cout << b[i] << " ";
    return 0;
}

I was solving a problem on finding the minimum between two and I'm not getting the right output

the output looks like this:

-16748 32765 -1677019 0 -5614317 32765 -8869681 32560 684147 32560 -9854715 0 -8007477 32560 400271 32560 -8326571 0 -2139466 32765 8289564 0 

I've been trying this for 30 minutes but haven't been successful.

Note: I'm a beginner to c++

There are multiple statements which you need to correct.

Firstly

    for (int i=0; i<=42; i+=2)

Your array size is 42, so the indices to loop are from 0 to 41(inclusive). However, your loop also reaches 42, which will cause undefined behaviour(which is generally bad), so the correct way would be

    for (int i=0; i < 42; i+=2)

Similarly for when you print b ,

    for (int i=0; i<=21; i++) //incorrect
    for (int i=0; i < 21; i++) //correct

Lastly, the code to find minimum, it can be done far more easily like this,


for (int i=0; i < 42; i+=2)
{
    b[i/2] = min(a[i], a[i + 1]); 
}

// OR you can do this

for (int i=0; i < 21; i++)
{
    b[i] = min(a[2 * i], a[2 * i + 1]); 
}

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