-1

I want to get the result of a division of two integers. For example the integers 6 and 25. If I divide the integers I get 6/25 = 0 as the answer. I want the result to be 6/25 = 0.24. How can I do it?

Roy Hvaara
  • 139
  • 9

4 Answers4

1

Convert the values to floating point first. For example

result = (double)a / (double)b.
Hellmar Becker
  • 2,824
  • 12
  • 18
1

Cast any of them to a float

float result = a/(float)b;
Mark E
  • 3,403
  • 2
  • 22
  • 36
  • Thank you , this one worked ! :D – Flora Biletsiou Nov 08 '15 at 17:54
  • If this answers your question you should mark it as accepted answer, so if anyone comes with the same problem, can find easily the solution – Mark E Nov 08 '15 at 18:00
  • I suggest preferring `double` over `float`. If you're dividing a larg integer by a small one (such as 1), there's a good chance a `float` will give an inexact result. – Tom Karzes Nov 08 '15 at 18:06
  • @TomKarzes there's a good chance for that no matter what – harold Nov 08 '15 at 18:43
  • @harold if your doubles are 64-bit and your ints are 32-bit, then a double can hold any int exactly. And that's a very common situation (the computer I'm using right now is like that). But even if you're using a computer with 64-bit ints, you're still going to have fewer problems with `double`. I have never found a need to use `float`. – Tom Karzes Nov 08 '15 at 18:46
  • @TomKarzes yes, but that rarely saves you from a division (sometimes yes), for example take the very example the OP used: 6/25. Can't represent that with a float. Still can't represent that with a double, or indeed any size of binary floating point number. – harold Nov 08 '15 at 18:57
  • @harold Right, I was just walking about the case where the result is an exact integer. – Tom Karzes Nov 08 '15 at 19:04
0

You can multiply the numerator by 1.0 if you want to avoid casting.

printf("%f\n", a * 1.0 / b);
rohit89
  • 5,745
  • 2
  • 25
  • 42
0

It is as simple as

#include <stdio.h>

int main(int argc, char** argv)
{
    printf("%.2f\n",(float)6/25);
}
machine_1
  • 4,266
  • 2
  • 21
  • 42
  • The `./` "operator" as in `6./25` also would do the job. :-) No casting necessary. – alk Nov 08 '15 at 18:22