Home > Software engineering >  Type Casting in C resulting in zero
Type Casting in C resulting in zero

Time:10-30

I have a simple C program where, I type cast two integers into float and then calculate their division. But, the type casting is resulting in zero. Kindly, a little help would be much appreciated.

'''

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

float mean(float sum,float N); 
int main()
{
    int sum = 6;
    int N = 3;
    printf("\nsum: %d\nN: %d",sum,N);
    float m = mean((float)sum,(float)N);
    printf("\nMean: %d",m);
}
return 0;
}

float mean(float sum,float N){
    float m = sum / N;
    return m;
}

Here's the Output: Output

CodePudding user response:

Conversion codes following % indicates the type of variable to be displayed. you are tring to disply a float by using an int convertor.

%f float or double --> Signed floating point use %f in the printf function insted of %d or %i --> Singed decimal integer

CodePudding user response:

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

float mean(float sum,float N); 
int main()
{
    int sum = 6;
    int N = 3;
    printf("\nsum: %d\nN: %d",sum,N);
    float m = mean((float)sum,(float)N);
    printf("\nMean: %f",m);
}
return 0;
}

float mean(float sum,float N){
    float m = sum / N;
    return m;
}

%d prints an integer in base 10, %f prints a floating point value. So, for example if I used

printf( "%d, %f\n", 9, 9.8 );

The output would be 9, 9.800000. If you give printf 5.5 but use %d I think anything could happen.

  • Related