简体   繁体   English

在 C++ 中的数组中找到 2 个数字的最小值

[英]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.我已经尝试了 30 分钟,但没有成功。

Note: I'm a beginner to c++注意:我是 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).您的数组大小为 42,因此要循环的索引从 0 到 41(含)。 However, your loop also reaches 42, which will cause undefined behaviour(which is generally bad), so the correct way would be但是,您的循环也会达到 42,这将导致未定义的行为(这通常很糟糕),因此正确的方法是

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

Similarly for when you print b ,同样,当您打印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]); 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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