简体   繁体   English

正确的代码以打印互换的最大值和最小值

[英]Correct Code to Print the interchanged max and min values

I was given a problem to interchange the position of the max and min numbers in a given set of numbers and print out the old arrangement and new arrangement 我遇到了一个问题,即在给定的一组数字中互换最大和最小数字的位置,并打印出旧的排列和新的排列

The old one is like this : 5,5678,62,6000 旧的是这样的:5,5678,62,6000

and the new one is expected to be like this: 6000,5678,62,5 而新的预计将是这样的:6000,5678,62,5

I've tried running different variations of the print code to print it all to no avail, as I've been able to interchange the max and min position of the numbers 我尝试运行不同的打印代码变体以全部打印都无济于事,因为我已经能够互换数字的最大和最小位置

int main () {
    int m [4] = {5,5678,62,6000};
    int i;
    int max=m[0];
    int min=m[0];
    int pMin = 0;
    int pMax = 0;
    int temp = 0;
    {
        printf( "%d\n", m[i]) ;
    }
for (i=0; i<4; i++){
    {
        printf( "%d\n", m[i]) ;
    }
    if ( m[i] > max )
    {
        max = m[i] ;
    }
}
for (i=0; i<4; ++i){
    if ( m[i] < min )
    {
        min = m[i] ;
    }
}
    temp = min;
    min = max;
    max = temp;

    printf ("min = %d\n", min);
    printf ("max = %d\n", max);
    printf( "%d\n", m[i]) ;
    getch();

} }

If i'm able to do it right by only inputting this line of code temp = min; 如果我能够通过仅输入这一行代码temp = min; min = max; max = temp; I should be able to achieve the aim of switching the places of the maximum and minimum numbers, but i also want to print out the result such that the 2 numbers in the middle are unaltered just the first and last. 我应该能够达到切换最大和最小位数的目的,但是我也想打印出结果,使得中间的两个数字仅第一个和最后一个不变。

The old one is like this : 5,5678,62,6000 旧的是这样的:5,5678,62,6000

and the new one is expected to be like this: 6000,5678,62,5 而新的预计将是这样的:6000,5678,62,5

You should get a warning from your compiler (if not, enable warning flags, like the -Wall in GCC), about this printing statement, inside its own block: 您应该从编译器获得警告(如果没有,请在其自己的块中启用有关此打印语句的警告标志,例如GCC中的-Wall ):

{
    printf( "%d\n", m[i]) ;
}

I think you meant to loop over the array and print its contents, which you do afterwards. 我认为您打算遍历数组并打印其内容,然后再进行操作。 But when you try to find the max , you seem to have forget to loop over the array. 但是,当您尝试找到max ,您似乎忘记了遍历数组。


Your code invokes Undefined Behavior (UB) here: 您的代码在此处调用未定义行为 (UB):

printf("%d\n", m[i]) ;

since you go out of range, because i has the last value after the previous for loop (to find the min ), which was 4 (size of the array). 因为您超出范围,因为i在前一个for循环(以找到min )之后有最后一个值,所以它是4(数组的大小)。 So you are indexing the array beyond its end, namely m[4] , which explains the garbage value of the output. 因此,您正在对数组的末尾进行索引,即m[4] ,该数组解释了输出的垃圾值。


Here is the plan, which you were getting close, but let's list it here: 这是您正在接近的计划,但让我们在这里列出:

  1. Find the max element of the array, and remember the index of that element. 找到数组的最大元素,并记住该元素的索引。
  2. Find the min element of the array, and remember the index of that element. 找到数组的min元素,并记住该元素的索引。
  3. Swap the min and max element of the array. 交换数组的min和max元素。

Note: If there are more than one maximum elements, take into account the last one seen. 注意:如果最大元素数不止一个,请考虑最后一个元素。 Similarly for the minimum element. 最小元素也是如此。

Putting everything together, you get this: 将所有内容放在一起,您会得到:

#include <cstdio>

int main () {
    int m [4] = {5,5678,62,6000};
    int i;
    int max=m[0], max_idx;
    int min=m[0], min_idx;
    int temp = 0;
    for(int i = 0; i < 4; ++i)
    {
        printf( "%d\n", m[i]) ;
    }
    for (i=0; i<4; i++)
    {
        if ( m[i] > max )
        {
            max = m[i];
            max_idx = i;
        }
    }

    for (i=0; i<4; ++i)
    {
        if ( m[i] < min )
        {
            min = m[i];
            min_idx = i;
        }
    }
    temp = min;
    m[min_idx] = max;
    m[max_idx] = temp;

    printf ("min = %d\n", min);
    printf ("max = %d\n", max);
    printf("The new array is:\n");
    for(int i = 0; i < 4; i++)
      printf("%d\n", m[i]);

}

Output: 输出:

5
5678
62
6000
min = 5
max = 6000
The new array is:
6000
5678
62
5

try this code 试试这个代码

 # include<stdio.h>

    int main () {
        int m [4] = {5,5678,62,6000};
        int i;
        int max=m[0];
        int min=m[0];
        int pMin = 0;
        int pMax = 0;
        int temp = 0;
    // print before swap
    for (i=0; i<4; i++){
        {
            printf( "%d\n", m[i]) ;
        }

        if ( m[i] > max )
        {
            max = m[i] ;
            pMin = i;

        }
    }
    for (i=0; i<4; ++i){
        if ( m[i] < min )
        {
            min = m[i] ;
            pMax = i;
        }
    }

        m[pMax] = max;
        m[pMin] = min;
     // print after swap
        for (i=0; i<4; i++)
        {
            printf( "%d\n", m[i]) ;
        }

        return 0;
        }

If it is indeed a C++ program then use C++ features. 如果确实是C ++程序,则使用C ++功能。

The program can look the following way. 该程序可以如下所示。

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

int main()
{
    int m[] = { 5, 5678, 62, 6000 };

    for ( const auto &item : m ) std::cout << item << ' ';
    std::cout << '\n';

    auto minmax = std::minmax_element( std::begin( m ), std::end( m ) );

    if ( minmax.first != minmax.second ) std::iter_swap( minmax.first, minmax.second );

    for ( const auto &item : m ) std::cout << item << ' ';
    std::cout << '\n';
}

Its output is 它的输出是

5 5678 62 6000 
6000 5678 62 5 

As for your code then it at least in this code snippet does not make sense 至于您的代码,那么至少在此代码片段中没有意义

int main () {
    int m [4] = {5,5678,62,6000};
    int i;
    // ...
    int temp = 0;
    {
        printf( "%d\n", m[i]) ;
    }
    // ...

not speaking about that the variable i is not initialized. 不说变量i没有初始化。

And your code does not swap the maximum and the minimum elements in the array. 而且您的代码不会交换数组中的最大和最小元素。

If it is a C program then it can look the following way. 如果它是C程序,则可以采用以下方式。

#include <stdio.h>

int main( void )
{
    int m[] = { 5, 5678, 62, 6000 };
    const size_t N = sizeof( m ) / sizeof( *m );

    for ( size_t i = 0; i < N; i++ ) printf( "%d ", m[i] );
    putchar( '\n' );

    size_t min_i = 0;
    size_t max_i = 0;

    for ( size_t i = 1; i < N; i++ )
    {
        if ( m[i] < m[min_i] ) min_i = i;
        if ( m[max_i] < m[i] ) max_i = i;
    }

    if ( min_i != max_i ) 
    {
        int tmp  = m[min_i];
        m[min_i] = m[max_i];
        m[max_i] = tmp;
    }

    for ( size_t i = 0; i < N; i++ ) printf( "%d ", m[i] );
    putchar( '\n' );
}

The program output is the same as shown above 程序输出与上图相同

5 5678 62 6000 
6000 5678 62 5 

You can rewrite this C program as a C++ program using the loops used in the program. 您可以使用程序中使用的循环将此C程序重写为C ++程序。

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

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