查找人数名列第二,而无需使用数组 [英] Find second highest number without using array

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

问题描述

您给出整数作为输入序列,由-1终止。 (即,输入整数可以是正,负或0 A -1中的​​输入信号的输入的结束。)

-1不被认为是作为输入的一部分。

查找输入的第二大数字。你可能不使用数组。

测试用例通过,但成绩是0.0

这里的code

  INT的main()
{
    int类型的= -32768,B = -32768,TEMP = -32768;
    而(1)
    {
        scanf函数(%d个,&安培; A);
        如果(一个== - 1)
            打破;
        否则如果(一个大于0)
        {
            温度= B;
            B = A;        }
        其他
        {
            如果(A> B)
            {
                温度= B;
                B = A;
            }
            其他
            {
                温度= B;
            }
        }    }
    的printf(%D,温度);
    返回0;
}


解决方案

在你的方式价值空头支票。
例如,像这样

 的#include<&stdio.h中GT;#定义EOI -1 //结束输入诠释主要(无效){
    INT输入,第一,第二;    第一=秒=意向书;    而(1){
        如果(1 = scanf函数(%d个,&安培;!输入)){
            fprintf中(标准错误,无效的输入\\ n!);
            返回-1;
        }
        如果(输入== EOI)
            打破;
        如果(第一== EOI){
            第一=输入;
        }否则如果(第一< =输入){
            第二=第一; //幻灯片
            第一=输入;
        }否则如果(第二== || EOI第二<输入){
            第二=输入;
        }
    }
    如果(二== EOI){//第一== || EOI第二== EOI
        fprintf中(标准错误,没有有效的值输入了多个\\ n!);
        返回-2;
    }
    的printf(%d个\\ N,第二);
    返回0;
}

You are given a sequence of integers as input, terminated by a -1. (That is, the input integers may be positive, negative or 0. A -1 in the input signals the end of the input.)

-1 is not considered as part of the input.

Find the second largest number in the input. You may not use arrays.

Test cases pass but score is 0.0

Here's the code

int main()
{
    int a=-32768,b=-32768,temp=-32768;
    while(1)
    {
        scanf("%d",&a);
        if(a==-1)
            break;
        else if(a>0)
        {
            temp=b;
            b=a;

        }
        else
        {
            if(a>b)
            {
                temp=b;
                b=a;
            }
            else
            {
                temp=b;
            }
        }

    }
    printf("%d",temp);
    return 0;
}

解决方案

Bad check of value in your way. For example, like this

#include <stdio.h>

#define EOI -1 //End Of Input

int main(void){
    int input, first, second;

    first = second = EOI;

    while(1){
        if(1 != scanf("%d", &input)){
            fprintf(stderr, "invalid input!\n");
            return -1;
        }
        if(input == EOI)
            break;
        if(first == EOI){
            first = input;
        } else if(first <= input){
            second = first;//slide
            first = input;
        } else if(second == EOI || second < input){
            second = input;
        }
    }
    if(second == EOI){//first == EOI || second == EOI
        fprintf(stderr, "No valid value is entered more than one!\n");
        return -2;
    }
    printf("%d\n", second);
    return 0;
}

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

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