查找第二大数字 [英] Find second largest number

查看:135
本文介绍了查找第二大数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是的,已经有很多人讨论了这个问题,但是这个问题似乎有点不寻常.程序应从用户输入的五个数字中找到第二大数字.我们不能使用loopsif语句.也不能使用arraysgoto's,但是可以使用三元运算符. I/0的示例:

Yes, there are loads of people have already discussed this problem but this one seems to be a bit extraordinary. Program should find the second largest number from the five ones entered by user. We cannot use neither loops nor if statements. Also cannot use arrays and goto's, but can use ternary operator. The sample of I/0 :

输入:34 -52 87 -12 20输出:34

输入:-87 52 87 87 20输出:87

如您所见,用户可以输入两个相同的数字,程序应该能够以这种方式进行处理.这是C编程.

As you see user can input two same numbers and program should be able to treat it this way. This is C programming.

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


int main(void)
{

    int i1, i2, i3, i4, i5;
    int max, second_max;

    scanf("%d %d %d %d %d", &i1, &i2, &i3, &i4, &i5);

    max = i1;
    max = (i2 > max) ? i2 : max;
    max = (i3 > max) ? i3 : max;
    max = (i4 > max) ? i4 : max;
    max = (i5 > max) ? i5 : max;

    second_max = i1;
    second_max = (i1 > second_max && i1 < max) ? i1 : second_max;
    second_max = (i2 > second_max && i2 < max) ? i2 : second_max;
    second_max = (i3 > second_max && i3 < max) ? i3 : second_max;
    second_max = (i4 > second_max && i4 < max) ? i4 : second_max;
    second_max = (i5 > second_max && i5 < max) ? i5 : second_max;




    printf("\nmax: %d", max);
    printf("\nsecond_max : %d", second_max);




    return 0;
}

在这里我可以找到所有内容,当涉及到第二个输出样本时,它会失败.我有编程经验,但是从早上起无法解决此问题

Here i can find everything, when it comes to the second sample of output it fails. I have an experience of programming but cannot solve this problem since morning

推荐答案

很显然,如果您可以对数字进行排序,则很容易解决该问题.那么,如何仅使用三元运算符对数字进行排序呢?答案被称为分拣网络.

Clearly, the problem is easy to solve if you can sort the numbers. So how do you sort the numbers using only ternary operators? The answer is known as a sorting network.

代码如下:

#include <stdio.h>

void swap( int *a, int *b )
{
    int x = *a <= *b ? *a : *b;
    int y = *a <= *b ? *b : *a;
    *a = x;
    *b = y;
}

int main( void )
{
    int a = 1, b = 9, c = 3, d = 8, e = 3;

    swap( &a, &b );
    swap( &c, &d );
    swap( &b, &e );
    swap( &a, &b );
    swap( &d, &e );
    swap( &a, &c );
    swap( &c, &d );
    swap( &b, &c );
    swap( &c, &d );

    printf( "%d %d %d %d %d\n", a,b,c,d,e );
}

对数字进行排序后,第二大数字是d.

After the numbers are sorted, the second largest number is d.

请注意,如果不能使用子例程和/或指针,则只需复制swap函数的主体并将其粘贴到main中九次.然后根据需要更改字母.玩得开心.

Note that if you can't use subroutines and/or pointers, then just copy the body of the swap function and paste it into main nine times. Then change the letters as needed. Have fun with that.

这篇关于查找第二大数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆