D
D
David Park2020-08-31 19:23:18
C++ / C#
David Park, 2020-08-31 19:23:18

Magic int when dividing by float?

Hello. C began to study quite recently, and here, as it turned out, there is a lot of "magic" that I do not understand.

#include <stdio.h>
int main()
{
  int a = 13;
  float b = 4.7;
  printf("%d", b/a); //на выходе получаем 660764199 
  printf("%d", b*a); //а здесь - -1207959552
  return 0;
}

When you try to divide/multiply an int by a float (or a float by an int), and then printf printf through the conversion symbol
for integers, that is, %d, the program produces some incomprehensible cosmic numbers.
I realized that you need to use %f and everything will be fine.
But I want to understand where these numbers come from? Since, according to my logic, the answer should have simply discarded the fractional part
and displayed a rounded version. So, let's say, why if int a = 12 is divided by float b = 6, and output through %d it turns out 0, but through %f it comes out 2.0? Or why 13/4.7 is the number mentioned above, and not just 2?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
SagePtr, 2020-08-31
@Xproz

Weird numbers are taken when one type is stored in a memory cell, and printf expects to see another, therefore it incorrectly represents it. Printf will not round or otherwise convert types for you, what they tell him, he will output.

W
wisgest, 2020-09-01
@wisgest

and then in printf output through the conversion character for integers, i.e. %d

It's not a conversion character, nothing is converted: you yourself are telling (fooling) printf about the type of data passed.
The transformation is done like this
printf("%d", (int)(b*a));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question