after compiling this code,I get k=0. shouldn't it be k=0.8? what's wrong with the code?
#include <stdio.h>
#include <math.h>
void main()
{
int x=8;
int y=10;
int m=6;
float k;
k=x/y;
printf("k=%f",k);
}
after compiling this code,I get k=0. shouldn't it be k=0.8? what's wrong with the code?
#include <stdio.h>
#include <math.h>
void main()
{
int x=8;
int y=10;
int m=6;
float k;
k=x/y;
printf("k=%f",k);
}
Although you are assigning the result of the division to a float
, the result itself is computed in integers. This is because both operands are of type int
.
There are multiple ways of fixing this problem - for example, by assigning the dividend to k
, and then dividing it by the divisor, like this:
int x=8;
int y=10;
int m=6;
float k = x;
k /= y;
printf("k=%f",k);
Type casting would be more useful and simple.
int x=8;
int y=10;
int m=6;
float k;
k=(float)x/y;
printf("k=%f",k);