简体   繁体   English

数组中最小和第二小的c程序

[英]c program for smallest and second smallest in array

#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);
}

input:0 0 1 2 输入:0 0 1 2

output:smallest is 0, second smallest is 0 输出:最小为0,第二最小为0

i want to get 0,1 as output.i do not want to use sorting here. 我想获得0,1作为输出。我不想在这里使用排序。 how can i improve my code. 我如何改善我的代码。

You are not handling the case of duplicate number. 您不处理重复号码的情况。 So I have modified your code. 所以我修改了您的代码。 Please try this and let me know. 请尝试这个,让我知道。

#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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM