【问题标题】:Dynamic arrays C动态数组 C
【发布时间】:2014-03-30 17:17:41
【问题描述】:

所以我正在创建数组,我需要找到除数最多的数字,以递减顺序打印数字、计数和除数,如果我创建只有 1 个数字的数组,我的函数可以正常工作,但是如果我创建它有 2 个或更多的除数会变成不正确的除数。

void calculate(int *data, int size){
    int max;
    int divisors[size][size];
    int divisorssize[size];
    //Checking for the divisors
  for (int i = 0; i < size; i++){
    divisorssize[i] = 0;
    for (int j = data[i]; j >= 1; j--) {
      if (data[i] % j == 0) {
        divisorssize[i]++;
        divisors[i][divisorssize[i]] = j;
      }
    }
  }
//Searching for the number in the array with the highest divisors count
  max = 0;
  for (int i = 0; i < size; i++){
    if (divisorssize[max] < divisorssize[i]){
      max = i;
    }
  }
//divisors Output
  printf("Max divisors: %d\n", data[max]);
  printf("divisors count: %d\n", divisorssize[max]);
  printf("divisors list: ");
  for (int i = 1; i <= divisorssize[max]; i++){
    printf("%d ", divisors[max][i]);
  }
}

功能使用:

calculate(data, size);

所以当我创建 size = 1 的数组时;输入数字 56 它​​显示所有除数:56 28 14 8 7 4 2 1,但如果例如大小为 2,我输入 56 和 1,它会将除数更改为 56 28 1 8 7 4 2 1。

【问题讨论】:

  • 请将代码拆分为函数。使 numDivisors(int x) 返回数字 x 的除数数。它会让你和其他人更容易。另外,你想要的似乎不是动态数组,它们是不同的概念
  • calculate: 多么美妙的描述性名称。
  • int divisors[size][size];int divisorssize[size]; 编译真的很奇怪。编译器不知道数组的大小,因此不知道需要分配多少内存空间。编译器不应该让你这样做。
  • 我们现在是 21 世纪的 Alex :)

标签: c arrays function function-pointers


【解决方案1】:

问题在于您的数组大小。

例如,大小为 2

int arr[size][size];

 int arr[2][2];

没关系,只要没有超过两个除数的数...

第二个维度的大小需要足够大以容纳任何除数。 例如,在 *data 中找到最大的数字,并使用它

 int array[size][max_number];

【讨论】:

    猜你喜欢
    • 2011-10-08
    • 1970-01-01
    • 2011-01-18
    • 1970-01-01
    • 2013-07-20
    • 2018-07-29
    • 1970-01-01
    • 2011-02-09
    相关资源
    最近更新 更多