# [beginner] float and division

• 04-27-2009
codezero
[beginner] float and division
hi this is my first post :)

Code:

```#include <stdio.h> #include <stdlib.h> int main() {    int a,b;    printf("Insert 2 numbers:\n");  scanf("%d%d",&a,&b);  printf("Result is: %f \n",a/b);    system("pause");  return 0; }```
the result isn't correct i always obtain 0.00 also if, for example, i write 8 and 2 as scanned number. why?
• 04-27-2009
quzah
Try printing a and b to see that you're actually getting numbers. Also, integer division will always yield integer results.

Quzah.
• 04-27-2009
JVene
cast a/b to floats with something like

(float) a / (float) b;

That provides a float result.

As it is, you're probably sending an integer when printf is expecting a float, which might easily produce nonsense.
• 04-27-2009
matsp
Quote:

Originally Posted by JVene
which might easily produce nonsense.

Change "might" into "will" - floating point numbers are quite different from integers in their internal components. So there is no chance that a floating point number will make much sense as an integer or the other way around. It'll look as nice as monkeys typing on a calculator.

It would actually make sense to use a cast to double rather than float, since printf doesn't ever take a float argument - all floating point values will convert to double before printf gets to see the value. And you only need to cast one side of the operator, so:
Code:

`printf("%f\n", (double)a / b);`
should give the right result.

--
Mats
• 04-27-2009
JVene
Ah, true - doubles....yish, I should probably stay in the C++ forum, my C is rusty.
• 04-27-2009
King Mir
Quote:

Originally Posted by matsp
Change "might" into "will" - floating point numbers are quite different from integers in their internal components. So there is no chance that a floating point number will make much sense as an integer or the other way around. It'll look as nice as monkeys typing on a calculator.

NITPICK: 0 can be represented the same way a integers and floating point. (And usually is, though sometimes -0 is used, which is equal the minimum integer value instead.)