gpt4 book ai didi

c - C中结构体数组的排序

转载 作者:行者123 更新时间:2023-11-30 19:33:40 25 4
gpt4 key购买 nike

下面的函数按体积对我的结构进行排序。

void selection_sort(struct cylinder my_cylinders[], int n)
{
int i, largest = 0;
double temp;

if (n == 1)
return;

for (i = 1; i < n; i++)
if (my_cylinders[i].volume > my_cylinders[largest].volume)
largest = i;

if (largest < n - 1) {
temp = my_cylinders[n - 1]; // ** Line 77
my_cylinders[n - 1] = my_cylinders[largest];
my_cylinders[largest] = temp; // ** Line 79
}

但是当我尝试编译时出现以下错误:

cylinders.c:77: error: incompatible types when assigning to type ‘int’ from type ‘struct cylinder’
cylinders.c:79: error: incompatible types when assigning to type ‘struct cylinder’ from type ‘int’

这是我的结构

struct cylinder {
double radius;
double height;
double weight;
double volume;
};

还有主要内容

int i, counter = 0; 

fprintf(cFileOut, "# Radius Height Volume Weight\n");

for (i = 0; i < 6; i++)
{
while (fscanf(cFileIn, "%lf, %lf, %lf\n", &radius, &height, &weight) != EOF)
{
my_cylinders[counter].radius = radius;
my_cylinders[counter].height = height;
my_cylinders[counter].volume = volume;
my_cylinders[counter].weight = weight;

volume = PI * radius * radius * height;
fprintf(cFileOut, "%-d\t %-12.6lf\t %-12.6lf\t %-12.6lf\t %-12.6lf \n",
counter, radius, height, volume, weight);
counter++;
}
}

selection_sort(my_cylinders, counter);

我想我理解这些错误,但不知道如何修复它们。我尝试过更改类型,但在结构方面我遗漏了一些东西。

最佳答案

将 temp 类型从 double 更改为 struct圆柱

另请注意,您只是根据体积从结构中查找最大的项目并将其与最后一个索引交换。这不是排序。

要排序,必须在循环中调用此函数,同时每次将计数器减 1。

类似于”

while(counter>=0){
selection_sort(my_cylinders, counter);
counter--;
}

并将函数内的 if 条件更改为:

if (n == 0)// since n=0 will mean that last item has been reached
return;

关于c - C中结构体数组的排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45128962/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com