所以我的代码有问题,无法弄清楚为什么......我认为从double变为int这一事实的可能性可能会改变函数,因为它对整数有效。
代码:
void
do_catavg(csv_t *D, int cat, int col) {
int i,j,k;
int count=0,nvalues[MAXROWS];
double category[MAXROWS],category_red[MAXROWS];
double average[MAXROWS];
double sum;
printf("%s %s\n",D->labs[cat-1],D->labs[col-1]);
for(i=0;i<D->nrows;i++){
category[i]=D->vals[i][cat-1];
printf("%f ",category[i]);
}
printf("\n");
sort_int_array(category,D->nrows);
printf("\n");
distinct(category,category_red,D->nrows);
printf("%d\n",distinct(category,category_red,D->nrows));
for(i=0;i<distinct(category,category_red,D->nrows);i++){
for(j=0;j<D->nrows;j++){
sum=0;
count=0;
if(category_red[i]==category[j]){
sum+=D->vals[j][col-1];
count++;
}
average[i]=sum/count;
nvalues[i]=count;
}
printf("%f %d\n",average[i],nvalues[i]);
}
return;
}
功能:
void
sort_int_array(double A[], int n) {
int i, j;
/* assume that A[0] to A[n-1] have valid values */
for (i=1; i<n; i++) {
/* swap A[i] left into correct position */
for (j=i-1; j>=0 && A[j+1]<A[j]; j--) {
/* not there yet */
int_swap(&A[j], &A[j+1]);
}
printf("%f ",A[i]);
}
printf("--BReak--");
printf("The first value is %f ",A[0]);
/* and that's all there is to it! */
}
int distinct(double A[],double B[], int n){
int i;
int new=0;
for(i=0;i<n;i++){
if(A[i]!=A[i+1]){
B[new]=A[i+1];
new++;
printf("%f ",B[i]);
}
}
return new;
}
/* exchange the values of the two variables indicated
by the arguments */
void
int_swap(double *p1, double *p2) {
double tmp;
tmp = *p1;
*p1 = *p2;
*p2 = tmp;
}
输出:
location mintemp
18.000000 22.000000 18.000000 22.000000 18.000000 22.000000 18.000000 22.000000
18.000000 22.000000
18.000000 18.000000 18.000000 18.000000 18.000000 18.000000 18.000000 18.000000
18.000000 --BReak--The first value is 22.000000
0.000000 0.000000 0.000000 0.000000 2
0.000000 0.000000 14.200000 1
0.000000 0.000000 -1.#IND00 0
0.000000 0.000000 > k 5 6
请不要关心 distinct 功能,因为此时它已被破坏。但我不明白为什么排序数组不起作用......
PS我完全相信其余的代码都很好并且有效,除了排序数组。
谢谢!
答案 0 :(得分:0)
以下代码干净利落地编译,
正确实现了插入排序,
相同的算法,通过改变类型,可以用来排序int等
#include <stdio.h>
struct csv_t
{
int nrows;
double labs[10] ;
};
void sort_double_array(double *A, int n);
struct csv_t D = {10, {200.0, 100.0, 50.0, 25.0, 12.0, 6.0, 3.0, 2.0, 1.0, 0.0}};
int main( void )
{
sort_double_array( D.labs, D.nrows );
return(0);
} // end function: main
void sort_double_array(double *A, int n)
{
int i, j;
/* assume that A[0] to A[n-1] have valid values */
double temp;
for(i=1;i<n;i++)
{
temp=A[i];
j=i-1;
while( (temp < A[j]) && (j>=0) )
{ // then entries need swapping
A[j+1] = A[j];
j=j-1;
} // end while
A[j+1]=temp;
} // end for
printf("--BReak--");
printf("sorted array\n");
for( i=0; i<n; i++ )
{
printf( "%f ", A[i]);
} // end for
/* and that's all there is to it! */
} // end function: sort_double_array
答案 1 :(得分:0)
您在排序算法中使用int_swap。使用等同于双打的东西。除此之外,函数sort_int_array似乎是正确的。