以下代码解决了在输入数字之间找到友好对的问题。我还不知道算法是否是最好的算法,但我的问题究竟是下面的代码继续返回分段错误:11。我检查它甚至没有进入readNums
函数的for循环。有什么建议是错的吗?
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
/*saves memory for a given length */
int *saveMemory(int sz) {
int *ptr = calloc(sz, sizeof(int));
if (ptr == NULL) {
printf("Error: memory allocation failed (out of memory?).\n");
exit(-1);
}
return ptr;
}
int *readNums(int length){
int *nums = saveMemory(length), i;
for (i = 0; i < length; i++){
scanf("%d", &nums[i]);
}
return nums;
}
int divArr (int n) {
int i=0;
int j;
int *arr = saveMemory(sizeof(arr)*4);
for (j=1; j<n; j++) {
if (n%j==0){
arr[i]=j;
i++;
}
}
return arr;
}
int sumDiv (int *arr){
int sum, i;
for (i=0; i< sizeof(arr); i++){
sum += arr[i];
}
return sum;
}
int main(int argc, char *argv[]) {
int i, j, k, length;
int *nums;
printf("Please give me the length \n");
scanf("%d", &length);
printf("Please type in the numbers to be checked \n");
nums = readNums(length);
for (k=0; k<length-1; k++) {
int a,b;
int *arr;
a=divArr(nums[i]);
b=divArr(nums[k]);
if (((sumDiv(a)) == nums[k]) && ((sumDiv(b)) == nums[i])) {
printf("%d %d \n", i, j);
} else {
i++;
}
}
}
答案 0 :(得分:0)
我没有检查你的逻辑