簡體   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);
}

輸入:0 0 1 2

輸出:最小為0,第二最小為0

我想獲得0,1作為輸出。我不想在這里使用排序。 我如何改善我的代碼。

您不處理重復號碼的情況。 所以我修改了您的代碼。 請嘗試這個,讓我知道。

#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