[英]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.