0

I'm trying to do a "simple" division in c and the result is going wrong, I have a float variable that receives the value of a division, in this case the division is a number contained in a long int, but the decimal part is cut when I try to print the variable

#include <stdio.h>

int main() {
    long int a = 120510380;
    float b;
    b = a / 7;
    printf("%f", b);
    return 0; 
}

Expected decimal number with numbers cut off after comma

Dai
  • 141,631
  • 28
  • 261
  • 374
  • _"I have a float variable that receives the value of a division"_ - yes, but `a / 7` is still integer division. – Dai Dec 09 '22 at 23:44
  • So how can I get the result with the missing decimal places? – Wellington Silva Dec 09 '22 at 23:52
  • 1
    Do `float b = (float)a / 7;` or `float b = a / 7f;` to force `float` division instead of `int` division; see here: https://stackoverflow.com/questions/13530209/how-to-convert-int-to-float-in-c – Dai Dec 09 '22 at 23:57
  • I really appreciate the attempt, but it doesn't work at all, if you want, you can try to run this section by putting "(float)" which keeps resetting the decimal places – Wellington Silva Dec 10 '22 at 00:17
  • 1
    You need to use `double` instead of `float`: an IEEE-754 Single (aka `float`) cannot represent more than ~7 s.f. but `120510380 ÷ 7 == 17,215,768.57142...` which requires more than 7 s.f. – Dai Dec 10 '22 at 00:38
  • See here: https://onlinegdb.com/Ubc1bcVwC- – Dai Dec 10 '22 at 00:39

0 Answers0