简体   繁体   English

交换C中最大和最小的数字

[英]Swapping largest and smallest numbers in C

I want to write a program that reads 10 int values from the user and swaps the largest and smallest numbers on the first and second values, then the rest of the numbers should be in the order. 我想编写一个程序,该程序从用户读取10个int值,并在第一个和第二个值上交换最大和最小的数字,然后其余数字应按顺序排列。

Please check the code and help me what the wrong is. 请检查代码,并帮助我找出问题所在。

For instance: 例如:

1
9
4
5
6
7
8
2
4
5

New order should be 9 1 4 5 6 7 8 2 4 5 新订单应为9 1 4 5 6 7 8 2 4 5

    #include <stdio.h>

    int main() {

    int a[10],i,min,max=0,pos=0;

    printf("Please enter 10 int values :\n");
    do{
    scanf("%d", &a[pos++]);
    } while (pos<10);

    for (i=0; i<10;i++) {
    printf("%i\n",a[i]);

    if (max<a[i])
    {
max=a[i];
}

    if (min>a[i])

    {
min=a[i];
    }

    for (i=0;i<10;i++) {

    if (a[i]==max) 
a[i]=max;

    if (a[i] == min) a[i] = min;

    }  

    printf("The new order is : %d %d %d ", max, min, ...);

    return 0;   
    }

EDIT: 编辑:

It is the new form

    #include <stdio.h>

    int main() {

        int a[10],i,pos,temp,min = 0,max = 0;

        printf("Please enter 10 int values :\n");

        do {

        scanf("%d", &a[pos++]);

        } while (pos < 10);

        for ( =1; i<10;i++) {

        if (a[i]>a[max]) 
{
max=i;
}

        if (a[i]<a[min]) 
{
min=i;
}
        }

        temp=a[max];

        a[max]=a[min];

        a[min]=temp;

        printf("%d %d",a[max],a[min]);

        for (i=0;i<10;i++){

        if ((i != min) && (i != max)) {

        printf("%d ", a[i]);
        }

        }

        printf("\n");

        return 0;   
    }

As others have noted, your code does not properly identify the maximum and minimum values in the array because you are writing min and max back into the array instead of the other way around. 正如其他人指出的那样,您的代码无法正确识别数组中的最大值和最小值,因为您正在将minmax写回到数组中,而不是相反。

Since you want to swap these values, what you actually want are the indices of the min and max values of the array, and swap those. 由于要交换这些值,因此实际需要的是数组的最小值和最大值的索引 ,然后交换它们。

It is best to break this code into functions instead of having everything in main. 最好将此代码分解为函数,而不是将所有内容都保留在函数中。 Here is a solution that will do what you want: 这是可以满足您需求的解决方案:

#include <stdio.h>

int indexofmax(int *data, int len)
{
    int max = 0;
    int i;
    for(i = 0; i < len; i++)
    {
        if(data[i]>data[max]) max = i;
    }
    return max;
}


int indexofmin(int *data, int len)
{
    int min = 0;
    int i;
    for(i = 0; i < len; i++)
    {
        if(data[i]<data[min]) min = i;
    }
    return min;
}

void swap(int *a, int *b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}

int main()
{
   // user enters in 10 ints...
   int max = indexofmax(a, 10);
   int min = indexofmin(a, 10);
   int i;
   swap(&a[min], &a[max]);
   for(i = 0; i < 10; i++)
   {
       printf("%d ", a[i]);
   }
   return 0;
}

You're not actually altering the array. 您实际上并没有改变数组。

In the second loop, you say "if the current element is the max, set it to the max". 在第二个循环中,您说“如果当前元素是最大值,则将其设置为最大值”。 In other words, set it to its current value. 换句话说,将其设置为当前值。 Similarly for the min. 分钟也一样。

What you want is to swap those assignments. 您要交换的是这些作业。

if(a[i]==max) a[i]=min;

if(a[i]==min) a[i]=max;

Also, your initial values for min and max are no good. 另外,您的minmax初始值也不好。 min is unitialized, so its initial value is undefined. min是单位化的,因此其初始值是不确定的。 You should initialize min to a very large value, and similarly max should be initialized to a very small (ie large negative) value. 您应该将min初始化为一个非常大的值,类似地, max应该被初始化为一个非常小的(即大的负数)值。

A better way to do this would be to keep track of the index of the largest and smallest values. 更好的方法是跟踪最大和最小值的索引 These you can initialize to 0. Then you can check a[i] > a[max] and a[i] < a[min] . 可以将它们初始化为0。然后可以检查a[i] > a[max]a[i] < a[min] Then you print the values at indexes min and max , then loop through the list and print the others. 然后,您可以在索引minmax处打印值,然后遍历列表并打印其他内容。

int i, temp, min=0, max=0;

for (i=1; i<10; i++) {
    if (a[i] > a[max]) max = i;
    if (a[i] < a[min]) min = i;
}

printf("%d %d ", a[max], a[min]);
for (i=0; i<10; i++) {
    if ((i != min) && (i != max)) {
        printf("%d ", a[i]);
    }
}
printf("\n");

This initialization min=0,max=0 is not right. 初始化min=0,max=0是不正确的。

Instead have min = INT_MAX and max = INT_MIN . 取而代之的是min = INT_MAXmax = INT_MIN

By setting min=0 , you would never get the lowest number in the array if it is greater than 0. 通过设置min=0 ,如果它大于min=0 ,则永远不会获得数组中的最低数字。

Similarly by setting max=0 , you would never get the greatest number in the array if it is lower than 0. 同样,通过设置max=0 ,如果数组中的数字小于0,则永远不会得到最大的数字。

You are gaining nothing by this code: 通过以下代码您一无所获

for(i=0;i<10;i++)

{ if(a[i]==max) a[i]=max;

  if(a[i]==min) a[i]=min; }  

It is evident that this loop 显然,这个循环

for(i=0;i<10;i++)

{ if(a[i]==max) a[i]=max;

if(a[i]==min) a[i]=min; }  

does not make sense. 没有道理。

Moreover variable min is not initialized while variable max is initialized incorrectly. 此外,变量min未初始化,而变量max未正确初始化。

int a[10],i,min,max=0,pos=0;

For example the array can contain all negative elements. 例如,数组可以包含所有否定元素。 In this case you will get incorrect value of the maximum equal to 0. 在这种情况下,您将获得不正确的最大值,该值等于0。

And I do not see where the elements are moved to the right to place the maximum and the minimum to the first two positions of the array. 而且我没有看到将元素移到右侧的位置,以将最大值和最小值移到数组的前两个位置。

If I have understood correctly then what you need is something like the following. 如果我正确理解,那么您需要的是以下内容。 To move the elements you could use standard function memmove declared in header <string.h> . 要移动元素,可以使用标头<string.h>声明的标准函数memmove However it seems you are learning loops. 但是,看来您正在学习循环。

#include <stdio.h>

#define N 10

int main( void )
{
    int a[N] = { 4, 5, 9, 6, 7, 1, 8, 2, 4, 5 };

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

    size_t min = 0;
    size_t max = 0;

    for (size_t i = 1; i < N; i++)
    {
        if (a[max] < a[i])
        {
            max = i;
        }
        else if (a[i] < a[min])
        {
            min = i;
        }
    }

    if (max != min)
    {
        int min_value = a[min];
        int max_value = a[max];

        size_t j = N;
        for (size_t i = N; i != 0; --i)
        {
            if (i - 1 != min && i - 1 != max)
            {
                if (i != j)
                {
                    a[j - 1] = a[i - 1];
                }
                --j;
            }
        }

        a[--j] = min_value;
        a[--j] = max_value;
    }

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

The program output is 程序输出为

4 5 9 6 7 1 8 2 4 5
9 1 4 5 6 7 8 2 4 5

Just keep it nice and simple, like this: 只需保持它的简洁漂亮即可,如下所示:

#include <stdio.h>
#include <stdlib.h>

#define MAXNUM 10

int find_biggest(int A[], size_t n);
int find_smallest(int A[], size_t n);
void print_array(int A[], size_t n);
void int_swap(int *a, int *b);

int
main(void) {
    int array[MAXNUM], i, smallest, biggest;

    printf("Please enter 10 int values:\n");
    for (i = 0; i < MAXNUM; i++) {
        if (scanf("%d", &array[i]) != 1) {
            printf("invalid input\n");
            exit(EXIT_FAILURE);
        }
    }

    printf("Before: ");
    print_array(array, MAXNUM);

    smallest = find_smallest(array, MAXNUM);
    biggest = find_biggest(array, MAXNUM);

    int_swap(&array[smallest], &array[biggest]);

    printf("After: ");
    print_array(array, MAXNUM);

    return 0;
}

int
find_biggest(int A[], size_t n) {
    int biggest, i, idx_loc;

    biggest = A[0];
    idx_loc = 0;
    for (i = 1; i < n; i++) {
        if (A[i] > biggest) {
            biggest = A[i];
            idx_loc = i;
        }
    }

    return idx_loc;
}

int
find_smallest(int A[], size_t n) {
    int smallest, i, idx_loc;

    smallest = A[0];
    idx_loc = 0;
    for (i = 1; i < n; i++) {
        if (A[i] < smallest) {
            smallest = A[i];
            idx_loc = i;
        }
    }

    return idx_loc;
}

void
print_array(int A[], size_t n) {
    int i;

    for (i = 0; i < n; i++) {
        printf("%d ", A[i]);
    }
    printf("\n");
}

void
int_swap(int *a, int *b) {
    int temp;
    temp = *a;
    *a = *b;
    *b = temp;
}

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

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