c - int 指针计算平均值

标签 c

我在计算函数中的平均值结果有问题,没有返回正确的数字,并且 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));
}

最佳答案

主要问题:

  1. 这个:

    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]);
    }
    
  2. 这里:

    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));
    }
    

其他问题:

  1. 您需要调用 seed rand 以在程序的每次运行中获得一组不同的随机值,这样您就不会在程序的每次运行中获得相同的随机数集。添加srand(time(NULL)); 在包含time.h 之后的main 开始处。这将返回一组不同的随机数,前提是该程序在同一秒内运行的次数不超过一次。
  2. 为什么要通过引用将 tam 传递给 calcular 是没有意义的。改为按值传递。
  3. There is no need cast the result of malloc (and family)在 C.
  4. 考虑检查 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/

相关文章:

从现有(但旧)示例代码创建 DLL

c - 使用 LINQ to Entities 的可选过滤器

c++ - 三次贝塞尔曲线交互

c - gcc 汇编字符串表示

我可以使这个包含很多 OR 的 if 语句更简洁吗?

c - 调用memcpy报错

c - 调整 malloc 指针

将 PSTR 转换为 PWSTR 并转义某些字符

c - 如何将文件中的纯文本解析为二维矩阵/数组?

c++ - 将 Linux 兼容项目从 Windows 移植到 Linux