C语言 如何在不使用数组的情况下使用c程序找到第二大元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25490946/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to find the Second Largest Element using c program without using array
提问by Nidhi Murthy
#include<stdio.h>
int main(){
int a[50],size,i,j=0,big,secondbig;
printf("Enter the size of the array: ");
scanf("%d",&size);
printf("Enter %d elements in to the array: ", size);
for(i=0;i<size;i++)
scanf("%d",&a[i]);
big=a[0];
for(i=1;i<size;i++){
if(big<a[i]){
big=a[i];
j = i;
}
}
secondbig=a[size-j-1];
for(i=1;i<size;i++){
if(secondbig <a[i] && j != i)
secondbig =a[i];
}
printf("Second biggest: %d", secondbig);
return 0;
}
i wrote above program using array. but i want to write without using array.
我用数组写了上面的程序。但我想写而不使用数组。
conditions are given a sequence of integers as input, terminated by a -1. i.e the input integers may be +ve, -ve or 0. A -1 in the input signals the end of the input. and -1 is not considered as part of the input.
条件以整数序列作为输入,以 -1 结尾。即输入整数可以是+ve、-ve 或0。输入中的-1 表示输入结束。-1 不被视为输入的一部分。
回答by Mike Dunlavey
foreach value v
if (v > biggest)
second = biggest
biggest = v
else if (v > second)
second = v
Note: you do have to decide what to do if there are repeated elements. In other words, suppose the numbers are 5,5,3,1. Then the largest is obviously 5, but is the second largest 5, or 3? That's for you to decide and fix the algorithm accordingly.
注意:如果有重复的元素,您必须决定该怎么做。换句话说,假设数字是 5、5、3、1。那么最大的显然是5,但是第二大的是5,还是3呢?那是由您决定并相应地修复算法。

