I need help

+1 Tomislav Keškić · February 3, 2015
Okay here's the code, for some reason it doesn't calculate the average correctly can someone help me?



#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
#include <string.h>

int main()
{
    int i, howMany;
    int total;
    float average = 0.0;
    int * pointsArray;


    printf("How many numbers do you want to average:");
    scanf("%d", &howMany);

    pointsArray = (int *) malloc(howMany * sizeof(int));
    printf("Enter them:\n");

    for(i= 0; i<howMany; i++){
        scanf(" %d", &pointsArray);
        total += pointsArray;
    }
    average = (float)total / (float)howMany;
    printf("The average is: %f", average);
    return 0;
}

Post a Reply

Replies

Oldest  Newest  Rating
0 Tomislav Keškić · February 3, 2015
nvm I just had to initilize the total..
+1 c student · February 4, 2015
you don't need to cast malloc to an int pointer.  also, don't forget to free your mallocs.
0 Tomislav Keškić · February 4, 2015
so to free it I just do free(pointsArray);?
Okay, I'll update the code in a sec, thanks for advice!
0 Tomislav Keškić · February 4, 2015

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int main()
{
    int i;
    int howMany;
    int total = 0;
    float average =0.0;
    int * pointsArray;

    printf("Enter how many numbers do you want to average?");
    scanf("%d", &howMany);
    check:
    if(isdigit(howMany)){
    if(howMany <2){
        printf("You need at least 2 numbers!\nTry again:");
        scanf("%d", &howMany);
        goto check;
    }

    pointsArray = (int *) malloc(howMany * sizeof(int));

    printf("Enter the numbers:\n");

    for(i=0; i<howMany; i++){
        scanf(" %d", &pointsArray);
        total += pointsArray;
    }

    average = (float)total / (float)howMany;
    printf("The average is: %f", average);
    free(pointsArray);
    }else if(isalpha(howMany)){
    printf("You have to enter NUMBERS, no letters!");
    goto check;
    }
    return 0;
}

Can someone help me out? It doesn't work this way for some reason, and I don't know why...
0 c student · February 5, 2015
ok, i see your problem.  you need to do some research on isdigit(), isalpha(), etc...
  • 1

C

107,095 followers
About

One of the most popular languages of all time.

Links
Moderators
Bucky Roberts Administrator