此代码试图通过花费较少时间完成比赛的玩家来找到比赛的获胜者和第二名。
#include <stdio.h>
int main(void){
int id[8] = {0};
float time[8] = {0};
for(size_t i=0; i<8; ++i) {
printf("nWrite id player: ");
scanf("%d", &(id[i]));
printf("nWrite time: ");
scanf("%f", &(time[i]));
}
size_t num1 = 0;
size_t num2 = 0;
for(size_t j=0; j<8; ++j){
if (time[num1]>time[j]){
num1 = j; // to find the winner
}
if (time[num2]>time[j] && time[num2]>time[num1]){
num2 = j; // to find the second position player
}
}
printf("nnWinner: %d, with time: %f", id[num1], time[num1]);
printf("nnSecond: %d, with time: %f", id[num2], time[num2]);
printf("nn");
}
不明白为什么这不起作用,它只适用于获胜者,但不适用于第二名球员。
输出:
Write id player: 1838
Write time: 4
Write id player: 3492
Write time: 6
Write id player: 3219
Write time: 2
Write id player: 48929
Write time: 9
Write id player: 38928
Write time: 4
Write id player: 23892
Write time: 4
Write id player: 89498
Write time: 1
Write id player: 48929
Write time: 6
Winner: 89498, with time: 1.000000
Second: 89498, with time: 1.000000
time[num2]>time[j] && time[num2]>time[num1]
条件不应该做这项工作吗?&&
不应该确保第二个获胜者的时间是 j 的小,但也大于获胜者。
你的逻辑是错误的,你需要一个初始值来比较,一个工作的例子(用整数简化只是为了显示逻辑(:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
srand((unsigned)time(NULL));
int arr[8] = {0};
for (size_t i = 0; i < 8; ++i)
{
arr[i] = rand() % 100;
printf("%dn", arr[i]);
}
puts("--");
int num1 = 0;
int num2 = 0;
int time1 = 100;
int time2 = 100;
for (int i = 0; i < 8; ++i)
{
if (arr[i] < time1)
{
time1 = arr[i];
num1 = i;
}
if ((arr[i] < time2) && (arr[i] > time1))
{
time2 = arr[i];
num2 = i;
}
}
printf("id: %d value %dn", num1, arr[num1]);
printf("id: %d value %dn", num2, arr[num2]);
}
请注意,在这种情况下,标准库可以提供帮助,qsort
是您的朋友,更少的变量,更少的代码,并且不易出错:
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int id;
float time;
} runner;
static int comp(const void *pa, const void *pb)
{
const runner *a = pa;
const runner *b = pb;
return a->time < b->time ? -1 : a->time > b->time;
}
int main(void)
{
runner runners[8] = {{0, .0f}};
for (size_t i = 0; i < 8; ++i)
{
printf("nWrite id player: ");
scanf("%d", &runners[i].id);
printf("nWrite time: ");
scanf("%f", &runners[i].time);
}
qsort(runners, 8, sizeof(runner), comp);
printf("nnWinner: %d, with time: %f", runners[0].id, runners[0].time);
printf("nnSecond: %d, with time: %f", runners[1].id, runners[1].time);
printf("nn");
}