读取数字并在pascal中进行比较

时间:2014-04-29 18:36:27

标签: pascal

我打算写一个程序,要求用户输入" n"数字,然后比较数字,找到我使用的第二大数字:

while i>n do read(number); i:=i+1;

是真的吗?如何保存数字并进行比较? 例如,如果用户有4个号码,请将它们保存为:

  

一个:=数字1;   B:=数字2; ...

1 个答案:

答案 0 :(得分:1)

从一个集合中找到第二大数字的算法(假设你正在追求的东西)相对简单。

get number into ultimate, on end-of-file exit
get number into penult, on end-of-file exit
if penult is greater than ultimate:
    swap ultimate and penult

while true:
    get number into num, on end-of-file return penult
    if num is greater than ultimate:
        set penult to ultimate
        set ultimate to num
    else:
        if num is greater than penult:
            set penult to num

换句话说,保留前两个数字[ultimate, penult]的“列表”,并将每个即将出现的数字插入该列表中,如果它们属于那里。

一旦用完了数字,该列表的第二项就是整个数字中第二高的数字。

如果您不希望重复占用两个广告位(例如1,2,11作为您真正想要的2的第二高位),那么您很可能如果它们匹配,可以扔掉那些副本:

get number into ultimate, on end-of-file exit
set penult to ultimate
while penult is equal to ultimate:
    get number into penult, on end-of-file exit
if penult is greater than ultimate:
    swap ultimate and penult

while true:
    get number into num, on end-of-file return penult
    if num is greater than ultimate:
        set penult to ultimate
        set ultimate to num
    else:
        if num is greater than penult and num is not equal to ultimate:
            set penult to testnum

重写在Pascal中,我会留下作为练习,因为它可能是课堂作业。