-2

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);
}
s-sc
  • 3
  • 1
  • because an implicit conversion in your code from float to integer to correct it: `k=(float)x/(float)y; printf("k=%g",k);` – Raindrop7 Dec 12 '16 at 21:39

2 Answers2

2

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);
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

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);
nerdicsapo
  • 427
  • 5
  • 16