为什么我的算术平均函数总是返回0?

时间:2018-10-20 20:53:05

标签: c average

在下面的代码中,函数calculo()不返回任何值。本来应该返回contaluno变量之间的算术平均值,但始终返回0。

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <time.h>

int i;

int calculo(int alunos, int *p) {
    int cont = 0;
    for (i = 0; i < alunos; i++)
        cont += p[i];
    return cont / alunos;
}

int main()
{
    int *p, alunos, media;

    printf("Digite a quantidade de alunos na turma \n");
    scanf("%d", &alunos);

    p = (int*)calloc(alunos, sizeof(int));

    if (p == NULL) {
        printf("Memória Insuficiente");
        return 1;
    }
    srand(time(NULL));
    for (i = 1; i < alunos + 1; i++) {
        *p = rand() % 10;
        printf("Nota do Aluno [%d]: \t %d \n", i, *p);
    }

    media = calculo(alunos, p);
    printf("A Media Aritimetica da turma e:\t %d", media);
    getche();
    free(p);
    return 0;
}

我在做什么错了?

1 个答案:

答案 0 :(得分:3)

srand(time(NULL));
for (i = 1; i < alunos + 1; i++) {
    *p = rand() % 10;  // <<=========================== here
    printf("Nota do Aluno [%d]: \t %d \n", i, *p);
}

您一次又一次地分配给*pp[0]。您可能想做的是

srand(time(NULL));
for (i = 0; i < alunos; ++i) {
    p[i] = rand() % 10;
    printf("Nota do Aluno [%d]: \t %d \n", i + 1, p[i]);
}