我在计算函数中的平均值结果有问题,没有返回正确的数字,并且 rand 返回值等于,我不知道平均值不好的原因
#include <stdio.h>
#include <stdlib.h>
int calcular(int * _arreglo, int * _tam);
int main(int argc, char * argv[]) {
int tam = 0;
if (argc == 2) {
tam = atoi(argv[1]);
} else {
printf("No se ha ingresado correctamente el tamaño \n");
exit(1);
}
int * arreglo;
arreglo = (int * ) malloc(sizeof(int) * tam);
int i;
for (i = 0; i < tam; i++) {
arreglo = (int * )(rand() % 101);
printf("soy %d \n", ((int)(arreglo)));
arreglo++;
}
int promedio = calcular(arreglo, & tam);
printf("Promedio: %d \n", promedio);
free(arreglo);
return 0;
}
int calcular(int * _arreglo, int * _tam) {
int pro = 0;
int i;
_arreglo = _arreglo - ( * _tam);
for (i = 0; i < * _tam; i++) {
pro = pro + ((int)(_arreglo));
_arreglo++;
}
return (pro / ( * _tam));
}
最佳答案
主要问题:
这个:
for(i=0;i<tam;i++){ arreglo=(int *)(rand()%101); printf("soy %d \n",((int)(arreglo))); arreglo++; }
没有任何意义。你可能想要
for(i = 0; i < tam; i++) { arreglo[i] = (rand() % 101); printf("soy %d \n", arreglo[i]); }
这里:
int calcular(int *_arreglo, int *_tam){ int pro=0; int i; _arreglo=_arreglo-(*_tam); for(i=0;i<*_tam;i++){ pro=pro+((int)(_arreglo)); _arreglo++; } return (pro/(*_tam)); }
你可能想要
int calcular(int *_arreglo, int *_tam){ int pro = 0; int i; for(i = 0; i < *_tam; i++){ pro = pro + _arreglo[i]; } return (pro / (*_tam)); }
其他问题:
- 您需要调用 seed
rand
以在程序的每次运行中获得一组不同的随机值,这样您就不会在程序的每次运行中获得相同的随机数集。添加srand(time(NULL));
在包含time.h
之后的main
开始处。这将返回一组不同的随机数,前提是该程序在同一秒内运行的次数不超过一次。 - 为什么要通过引用将
tam
传递给calcular
是没有意义的。改为按值传递。 - There is no need cast the result of
malloc
(and family)在 C. 考虑检查
malloc
的返回值以查看它是否成功。变化:arreglo = (int * ) malloc(sizeof(int) * tam);
到
if((arreglo = malloc(sizeof(int) * tam)) == NULL) /* If malloc failed */ { fputs("malloc failed; Exiting...", stderr); /* Print the error message in the `stderr` */ exit(-1); /* Exit the program */ }
关于c - int 指针计算平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32934366/