【发布时间】:2020-08-31 06:33:55
【问题描述】:
我有一个 C 程序可以读取 20 个 x-y 坐标的 CSV 文件。首先将元素放入一个链表,然后将它们放入一个数组,其中每行的 x 和 y 坐标相乘。乘法完成后,数组将按升序排序。但是由于某种原因,在打印出数组时,这些值没有正确排序并且似乎是随机顺序。我为此使用 qsort。我不确定为什么程序无法正确排序值。
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <sys/time.h>
#include <string.h>
#define MAX 200
typedef struct wake {
double x, y;
struct wake *next;
} data;
//typedef struct wake data;
void read_csv(data *head, data **tail);
void gridSearch();
void maxNode();
int num_elements(data *head);
int create_array(data *head, int num, double *array);
int compare_array(const void* a, const void* b);
int main(int argc, char *argv[]) {
int num = 0;
struct wake* head = NULL;
struct wake** tail = &head;
read_csv(head, tail);
num = num_elements(head);
//printf("%d\n", num);
double *array = malloc(num * sizeof(double));
create_array(head,num,array);
}
void read_csv(data *head, data **tail) {
// Opens the CSV datafile
FILE *fp = fopen("data4.csv", "r");
fscanf(fp, "%*[^\n]\n");
char buffer[MAX];
while (fgets(buffer, MAX, fp)) {
data *node = malloc(sizeof(data));
node->x = atof(strtok(buffer, ","));
node->y = atof(strtok(NULL, ","));
node->next = NULL;
*tail = node;
tail = &node->next;
}
}
int num_elements(data *head) {
struct wake *temp;
temp = head;
int num = 0;
while(temp!=NULL) {
//printf("%lf,%lf\n", temp->x,temp->y);
num++;
temp = temp->next;
}
return num;
}
int compare_array(const void* a, const void* b) {
int p1 = *((double*)a);
int p2 = *((double*)b);
if (p1 < p2) {
return -1;
}
else if (p1 > p2) {
return 1;
}
else {
return 0;
}
}
int create_array(data *head, int num, double *array) {
struct wake *temp;
temp = head;
int i = 0;
while(temp!=NULL) {
//printf("%d: %lf %lf\n", i, temp->x, temp->y);
array[i] = (temp->x)*(temp->y);
i++;
temp = temp->next;
}
qsort(array, num, sizeof(double), compare_array);
for (i=0; i<num; i++) {
printf("%d: %lf\n", i, array[i]);
}
return num;
}
这是输入的 CSV 文件:
x,y
0,0.95351
0.000413,0.953579
0.001741,0.953692
0.002695,0.953709
0.002806,0.95362
0.002277,0.953444
0.001662,0.953219
0.001404,0.953006
0.001418,0.952866
0.001181,0.952824
0.000302,0.952881
-0.001057,0.953021
-0.002364,0.953184
-0.003202,0.95329
-0.003514,0.953341
-0.003451,0.95343
-0.003154,0.953606
-0.002697,0.953808
-0.002145,0.953952
-0.001569,0.95404
【问题讨论】:
-
你在比较
int...