#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作为输出。我不想在这里使用排序。 我怎样才能改进我的代码。
答案 0 :(得分:2)
您没有处理重复号码的情况。所以我修改了你的代码。请试试这个并告诉我。
public void CreateTallPeople()
{
var tallPeopleList = new List<IPerson>
{
new TallPerson {Height = 210, Name = "Stevo"},
new TallPerson {Height = 211, Name = "Johno"},
};
InteratePeople(tallPeopleList);
}
public void InteratePeople(List<IPerson> people)
{
foreach (var person in people)
{
Console.WriteLine($"{person.Name} is {person.Height}cm tall. ");
}
}