【发布时间】:2017-04-12 13:49:58
【问题描述】:
找到结构数组中的前 5 个最大值(用于 C 编程)? 我有一个结构数组如下:
struct info {
char name[100];
int number;
}
struct info people[10]
在 char name[100] 中是人名(最多 10 个),它们在 int balance 中有对应的值:
Jane 10
John 40
Harry 16
Eva -5
...
直到达到 10 人。
如何找到并打印数字最高的 5 个人?
即:
John 40
Harry 16
Jane 10
...
我已经尝试了以下代码:
int i,j, k=5, max, temp;
//move maximum 5 numbers to the front of the array
for (i=0; i<k; i++) {
max=i;
for (j=i+1; j<10; j++) {
if (people[i].number>people[max].number) {
max=j;
}
}
//swap numbers
temp=people[i].number;
people[i].number=people[max].number;
people[max].number=temp;
//swap names to match swapped numbers so they correspond
temp=people[i].name;
people[i].name=people[max].name;
people[max]=temp;
}
for (i=0; i<k; i++) {
printf("%s %d\n", people[i].name, people[i].number);
}
但是,我在第二次交换时收到一条错误消息,因为它是 char 类型。我应该如何解决这个问题,或者还有什么方法可以实现这个目标?
【问题讨论】:
-
您使用
strcpy系列函数复制字符串。 -
为什么要交换结构?只需找到对应于数组中具有最大值的五个元素的五个索引。请记住允许重复值的可能性。
-
struct info temp = people[i]; people[i] = people[max]; people[max] = temp; -
使用这个例子排序..cplusplus.com/forum/general/97555
-
@4py - 对
c程序员不是很有帮助:(