所以我有一个问题:
我的程序必须找到数组中最常见的元素。我们必须使用calloc
创建此数组。我的代码正在运行,但我被要求将部分代码移动到一个函数中,我必须创建一个数组并输入数字。
int main() {
int n, i, dazn;
int *A;
dazn = 0;
printf("Iveskite naturalu skaiciu: \n");// enter how many elements in an array we will have
scanf("%d", &n);
A = (int*)calloc(n, sizeof(int)); // Starting from here...
for (i = 0; i < n; i++) {
printf("Iveskite skaiciu \n");
scanf("%d", &A[i]); //
}
... // and ending here have to be in a function
... // sorting and finding the most common element
答案 0 :(得分:0)
按照说明,将代码移动到单独的函数:
#include <stdio.h>
#include <stdlib.h>
int *allocate_and_read_array(int size) {
int *A = (int*)calloc(size, sizeof(int));
if (A != NULL) {
for (int i = 0; i < size; i++) {
printf("Iveskite skaiciu \n");
if (scanf("%d", &A[i]) != 1) {
printf("Missing values\n");
break;
}
}
}
return A;
}
int main(void) {
int n, i, dazn;
int *A;
dazn = 0;
printf("Iveskite naturalu skaiciu: \n");// enter how many elements in an array we will have
scanf("%d", &n);
A = allocate_and_read_array(n);
... // sort the array
... // find the most common element
free(A);
return 0;
}