-1

I am having a bit problem with this simple code.

I have tried different type castings, but I have not got any issue in here. If anybody tell me the reason that why its always printing 0.0000000 or something like that, I will be regretful and thanks in advance.

#include<stdio.h>
main()
{
    double num1,num5;
    printf ("Hello user\n");
    printf ("Let the thickness of black and white brick are same and the value 
             is 2m\nAnd the gap between them is 1m\n");
    printf ("\nEnter the length of the road:\n");
    scanf ("%lf",&num1);
    num5 = ((2/5)*num1);
    printf ("%lf",num5);
    return 0;
}
qfwfq
  • 2,416
  • 1
  • 17
  • 30
  • Duplicate with https://stackoverflow.com/questions/40443602/c-double-not-working-as-expect/40443639#40443639 and https://stackoverflow.com/questions/16221776/why-dividing-two-integers-doesnt-get-a-float – Guillaume Jacquenot Jun 04 '17 at 20:50
  • Possible duplicate of [Dividing 1/n always returns 0.0](https://stackoverflow.com/questions/13331054/dividing-1-n-always-returns-0-0) – phuclv Jun 05 '17 at 06:57

3 Answers3

2

(2/5) performs an integer calculation, result 0. I suggest one of these approaches

num5 = 0.4 * num1;

num5 = 2 * num1 / 5;

The second is potentially more accurate (since 0.4 cannot be exactly represented in double) when num1 is already a multiple of 5. In the first case, an error is already there.

Weather Vane
  • 33,872
  • 7
  • 36
  • 56
1

In integer math, 2/5 is 0 (remainder two). In C, how you use a result does not affect how that result is computed (the rules are complex enough already). So the fact that you multiply the result by a double doesn't change the way 2/5 (the quotient of two integers) is computed.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
0

2 and 5 are integers they are not double. Adding decimal point will yield the correct result.

Something like this.

num5 = ((2.0/5.0)* num1);

or

  num5 = ((2.0/5)* num1);

or

  num5 = ((2/5.0)* num1);
danglingpointer
  • 4,708
  • 3
  • 24
  • 42