1

Is it possible to output double/float number as an result of dividing of two integers? For example:

int a = 5
int b = 3
printf(" Dividing: %d / %d = %f",a ,b ,a/b);

Because in my program, it is showing error.

warning: format ‘%f’ expects argument of type ‘double’, but argument 2 has type ‘int’ [-Wformat=]
   47 |     printf("Percentage of odds: %f\n", (odd / random) * 100);
      |                                 ~^     ~~~~~~~~~~~~~~~~~~~~
      |                                  |                    |
      |                                  double               int
      |                                 %d
try.c:48:23: warning: format ‘%f’ expects argument of type ‘double’, but argument 2 has type ‘int’ [-Wformat=]
Juraj
  • 63
  • 6
  • No, because i don't want to save the value only to print it out. (trying to write it as efficient as possible) So I want to know if there exist any opportunity to print it out without saving it in third variable and having two integers(not integer and double to save memory). If not I will use mentioned methodes. – Juraj Aug 23 '20 at 18:51
  • Compared with adding floating-point support, an extra variable is of no significance. – Martin James Aug 23 '20 at 19:39

2 Answers2

1

There are two kinds of divisions of integer numbers: the integer division and the so-called normal division (the latter may result in a floating point number). Let me give you the following examples:

Normal division:

7 / 2 = 3.5

Integer division (only the integer part remains):

7 / 2 = 3

The C programming language makes following distiction: if both numbers are integers (normal, unsigned, short, whatever), then the integer division is used.
If at least one of the two is floating point (normal, double precision or whatever), then the "normal" division is used.

And what if you want to apply the normal division on two integers? Well, simply turn one ofthe two into a floating point number, as follows:

(double) a / b

This turns "a" into a double and as such applies the normal division.

And what about this:

(double) (a / b)

Well, this is first making the division (the integer division, as both numbers are integers) and turning the result (an integer number) into a double precision floating point, which is pretty useless ;-)

Dominique
  • 16,450
  • 15
  • 56
  • 112
0

In C, the result of a division of two integers yields to an integer (the decimal part of the result is dropped). 5/3 ~= 1.67 but becomes 1 because both a and b are integers. You have to make the compiler understand it's dealing with a double division and must evaluate to a double instead of an int.

It is possible to do so by casting one of the operands as a double, since double/int -> double or int/double -> double :

printf("Dividing: %d / %d = %f", a, b, (double)(a)/b);
Riptide
  • 385
  • 7
  • 17