Pregunta

I made the following program to calculate sum,mean and standard deviation of 5 numbers.The Sum is correct but mean is coming out to be zero ALWAYS and hence the SD is also wrong.

#include<stdio.h>
#include<conio.h>
#include<math.h>

int sum(int, int, int, int, int);
float SD(int, int , int, int,int,int);
float mean(int);

int main()
{
    int a,b,c,d,e,m;
    printf("Enter 5 integers succesively by pressing enter after entering a number.\n");
    scanf("%d %d %d %d %d",&a,&b,&c,&d,&e);
    m=mean(sum(a,b,c,d,e));
    printf("\nThe sum is %d , mean is %f and standard deviation is %f",sum(a,b,c,d,e),m,SD(a,b,c,d,e,m));
    return 0;   
}

int sum(int v, int w, int x, int y, int z)
{
    return(v+w+x+y+z);
}

float SD(int v, int w, int x, int y, int z,int mm)
{
    float k;
    k=sqrt(((mm-v)*(mm-v) + (mm-w)*(mm-w) + (mm-x)*(mm-x) + (mm-y)*(mm-y) + (mm-z)*(mm-z))/5);
    return k;
}

float mean(int v)
{
    return (v/5);
}
¿Fue útil?

Solución

when you use division make use float data type. in mean() and SD() function you do division by 5 and both operands are int so change one of those to float. otherwise result will be truncated to be a int.
You can change /5 to /5.0 or you can use a float type cast.

The mean you are getting as 0 since you defined m as integer int and using %f to print it.

int a,b,c,d,e,m;
printf("\nThe sum is %d , mean is %f and standard deviation is %f",sum(a,b,c,d,e),m,SD(a,b,c,d,e,m));

m is mean so make it a float type variable.

int a,b,c,d,e;
float m;

Otros consejos

Change v/5 to v/5. .

Since v and 5 are both int, then v/5 is an integer division. You want to do a floating-point division instead, so you have to make one of the operands be floating, and 5. is a constant of type double.

Same thing applies in your SD function.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top