如何使用C程序,而无需使用数组来找到第二个最大的元素 [英] how to find the Second Largest Element using c program without using array
问题描述
#包括LT&;&stdio.h中GT;
诠释主(){
int类型的[50],大小,I,J = 0,大,secondbig;
的printf(请输入数组的大小:);
scanf函数(%d个,&安培;大小);
的printf(到阵列输入%d个要素:大小);
对于(i = 0; I<大小;我++)
scanf函数(%d个,&安培; A []); 大= a [0];
对于(i = 1; I<大小;我++){
如果(大< A []){
大= a [i];
J =;
}
} secondbig =一个[大小-J-1];
对于(i = 1; I<大小;我++){
如果(secondbig< A [1] - 放大器;&安培;!J =)
secondbig =一个由[i];
} 的printf(第二最大数:%d,secondbig);
返回0;
}
我使用数组写上面的程序。但我不想使用数组来写的。
条件给出的整数作为输入序列,由-1终止。即输入整数可以是雾化+ ve,-ve或0 A -1中的输入信号的输入的结束。
和-1不被认为是作为输入的一部分。
的foreach值v
如果(V>最大)
第二=最大
最大= V
否则,如果(V>第二个)
第二= V
请注意:你必须决定是否有重复的元素做什么。
换句话说,假设号码5,5,3,1。
然后最大显然是5,但是第二大5,或3'
这是由你来决定,并相应修正算法。
#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.
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.
这篇关于如何使用C程序,而无需使用数组来找到第二个最大的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!