2017-03-04 12 views
0
#include <stdio.h> 
#include <string.h> 

void main() 
{ 
    int smallest, secondsmallest; 
    int array[100], size, i; 
    printf("\n How many elements do you want to enter: "); 
    scanf("%d", &size); 
    printf("\nEnter %d elements: ", size); 
    for (i = 0 ; i < size; i++) 
    scanf("%d", &array[i]); 
    if (array[0] < array[1]) { 
    smallest = array[0]; 
    secondsmallest = array[1]; 
    } 
    else { 
    smallest = array[1]; 
    secondsmallest = array[0]; 
    } 
    for (i = 2; i < size; i++) { 
    if (array[i] < smallest) { 
     secondsmallest = smallest; 
     smallest = array[i]; 
    } 
    else if (array[i] < secondsmallest) { 
     secondsmallest = array[i]; 
    } 
    } 
    printf(" \nSecond smallest element is %d", secondsmallest); 
    printf(" \n smallest element is %d", smallest); 
} 

入力:第二の最小は0Cプログラム最小とするための二番目の配列内の最小

iは0,1を取得したい最も小さいが、0:0 0 1 2

出力output.iはここでソートを使いたくないからです。 コードを改善するにはどうすればいいですか?

+0

配列のすべての要素が等しい場合はどうなりますか? – DyZ

+4

したがって、配列の重複する値を無視したいですか?あなたのコードはそれらを無視しません。そうすべき。 – Peter

答えて

2

重複した番号の場合は処理していません。だからあなたのコードを変更しました。これを試して私に知らせてください。

#include <stdio.h> 
#include <string.h> 
void main() 
{ 
int smallest, secondsmallest; 
int array[100], size, i; 
printf("\n How many elements do you want to enter: "); 
scanf("%d", &size); 
printf("\nEnter %d elements: ", size); 
for (i = 0 ; i < size; i++) 
    scanf("%d", &array[i]); 

if (array[0] < array[1]) { 
smallest = array[0]; 
secondsmallest = array[1]; 
} 
else { 
smallest = array[1]; 
secondsmallest = array[0]; 
} 
for (i = 2; i < size; i++) { 
if (array[i] < smallest) { 
secondsmallest = smallest; 
smallest = array[i]; 
} 
else if (smallest == secondsmallest){ 
smallest = secondsmallest; 
secondsmallest = array[i]; 
} 
else if (array[i] < secondsmallest && array[i] > smallest) { 
secondsmallest = array[i]; 
    } 
} 
printf(" \nSecond smallest element is %d\n", secondsmallest); 
printf(" \n smallest element is %d\n", smallest); 
} 
+0

このコードを改善して、より少ないループ@vinodmaverickを使用することができます – raju