0

我想制作一个程序,根据向量的长度对向量的维度和数量进行排序。大多数代码有效,但程序的排序部分无效。基本上我想做的是:比较数组 w 中 2 个位置的 bereken_lengte 函数的输出。但似乎什么也没有发生。同样在函数 bereken_lengte 中,我无法在循环结束后求和的根。

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

double bereken_lengte(double *array, int dim)
{
  int i, j;
  double sum = 0.0;
  for(i=0; i<dim; ++i)
    sum += pow(array[i],2);
  return sum;
}

void swap(double **p, double **q)
{
  double *tmp;
  tmp = *p;
  *p = *q;
  *q = tmp;
}

void sort_vector(double *w[] , int num , int dik )
{
  int i,dim,j;
  dim = dik;
  for(i=0;i<num;++i)
    for(j = 1+i;j<num;++j)
    {
      if(bereken_lengte(w[i],dim) > bereken_lengte(w[j],dim)  )
        swap(&w[i], &w[j]);
    }
}

int main (void)
{
  int dim, num;
  int i, j,k,l;
  double **w;
  scanf ("%d %d", &dim, &num);          /* read N and M */
  w = calloc (num, sizeof (double *));  /* allocate array of M pointers */
  for (i = 0; i < num; i++)
  {
    /* allocate space for N dimensional vector */
    w[i] = calloc (dim, sizeof (double));
    /* read the vector */
    for (j = 0; j < dim; j++)
    {
      scanf ("%lf", &w[i][j]);
    }
  }
  sort_vector(w,num,dim);
  for(k=0; k<num; ++k)
  {
    printf("\n");
    for(l=0; l<dim; ++l)
      printf("%f ", w[k][l]);
  }
  return 0;
}
4

1 回答 1

2
double bereken_lengte(double *array, int dim)
{
  unsigned int i;
  double sum =0.0;
  for(i=0; i<dim; ++i)
    sum += pow(array[i],2);
  return sum;
}

在求和之前将总和初始化为零。

顺便说一句,我将 i 更改为未签名。IMnsvHO 对索引 && 大小变量使用无符号类型是一个好习惯(它们不会下溢,如果这样做,您会注意到它)

更新:这试图避免 int 索引和大小,并使用 qsort。(相当丑陋,因为比较函数只需要两个元素;不要在多线程程序中尝试这个......)注意,我可能有行和列互换,但这是一种生活方式...... gewoon,omdat het kan !:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

double bereken_lengte(double *array, size_t dim)
{
  size_t i;
  double sum=0.0;
  for(i=0; i<dim; ++i)
    sum += pow(array[i],2);
  return sum;
}

        /* this is ugly: qsort only allows only two arguments */
static size_t ze_third_argument=0;
int srt_pdbl(void *l, void *r)
{
double **dl = l, **dr = r;
double diff;
diff = bereken_lengte( *dl, ze_third_argument) - bereken_lengte( *dr, ze_third_argument) ;
return (int) diff;
}

void sort_vector(double *w[] , size_t num , size_t dik )
{
ze_third_argument = dik;
qsort(w, num, sizeof *w, srt_pdbl );
}

int main (void)
{
  size_t dim, num;
  size_t i, j,k,l;
  double **w;
  scanf ("%zu %zu", &dim, &num);          /* read N and M */
  w = calloc (num, sizeof *w);  /* allocate array of M pointers */
  for (i = 0; i < num; i++)
  {
    /* allocate space for N dimensional vector */
    w[i] = calloc (dim, sizeof *w[i] );
    /* read the vector */
    for (j = 0; j < dim; j++)
    {
      scanf ("%lf", &w[i][j]);
    }
  }
  sort_vector(w,num,dim);
  for(k=0; k<num; ++k)
  {
    printf("\n");
    for(l=0; l<dim; ++l)
      printf("%f ", w[k][l]);
  }
  return 0;
}
于 2012-12-28T00:51:12.470 回答