muhamad
muhamad

Reputation: 75

middle mode avg calculating of an float array

I`ve wrote a code to calculate middle,mode and average of a float array but just when I input the first number I encounter with the"...has stopped working" error in dev c.in vs 2012 also it doesn t work.why?

#include<stdio.h>
float avg(float [],int);
void mode(float [], int);
float middle(float [], int);
int main(){
    int i,t=5;
    float a[t];
    for (i=0;i<t;++i)
        scanf("%f", a[i]);
    printf("avg= %f\n", avg(a, t));
    printf("middle= %f\n", middle(a, t));
    //printf("mode= \n", mode(a[]));
    mode(a, t);
    return 0;
}
float avg(float a[], int t){
    float s;
    int i;
    for(i=0;i<t;++i)
        s+=a[i];
    return s/t;
}
 float middle(float a[], int t){
    int i,u;
    float h;
    for(i=0;i<t-1;++i)
        for(u=1;u<t;++u)
            if(a[i]>a[u]){
                h=a[i];
                a[i]=a[u];
                a[u]=h;
            }
    if(t%2==0)
        return (a[t/2]+a[t/2+1])/2;
    else
        return (a[(t+1)/2]);
}
void mode(float a[], int t){
    float b[t],h;
    int i,u;
    for(i=0;i<t;++i)
        b[i]=0;
    for(i=0;i<t;++i)
        for(u=0;u<t;++u)
            if (a[i]==a[u])
                b[i]++;
    for(i=0;i<t-1;++i)
        for(u=1;u<t;++u)
            if(a[i]<a[u]){
                h=a[i];
                a[i]=a[u];
                a[u]=h;
            }
    printf("%f\n", a[0]);
    for(i=1;i<t;++i)
        if(a[0]==a[i])
            printf("%f\n", a[i]);
}

Upvotes: 0

Views: 95

Answers (1)

Gopi
Gopi

Reputation: 19864

scanf("%f", a[i]);

should be

scanf("%f", &a[i]);

scan to the location where you want to store the value and here it is &a[i]

 float s;

s is uninitialized in the function avg() and using uninitialized variables lead to undefined behavior.

Upvotes: 2

Related Questions