-3
#include <stdio.h>

int main(int argc, const char * argv[]) {

    int a = 10;
    int b = 20;
    double result = a / b;
    printf("%d divided by %d makes %f\n", a, b, result);

    return 0;
}

Expecting that the %f would return 0.500000, I ran the code and it turned out to be 0.000000.

Is there a reason that the result variable is returning a zero value?

MarshallLee
  • 1,290
  • 4
  • 23
  • 42

2 Answers2

10

Because it's performing integer devision since a and b are ints, try this

double result = (float) a / (float) b;
Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
  • 1
    To be more specific, the compiler doesn't care what type you're assigning the expression to. The precision of an operation is dependent only on the operand types. In this case, `int / int` uses integer division. By casting one (or both) of the arguments to `float`, the operation is promoted to floating-point division. – MooseBoys Jan 13 '16 at 00:50
  • Thanks for the answer. I have to wait a few more minutes to accept your answer now. – MarshallLee Jan 13 '16 at 00:52
  • Can I ask you one more question? If I run the the same code in Java, say, `double result = (float) a / (float) b;` and run `System.out.println(result);`, now it's returning a very strange value, something like `0.6000000238418579`. Can you also explain why? – MarshallLee Jan 13 '16 at 00:54
  • @newbieprogrammer No, sorry I don't know java. – Iharob Al Asimi Jan 13 '16 at 01:12
  • Alright.. better check out the other questions. Thanks for the answer anyways! I accepted it now :) – MarshallLee Jan 13 '16 at 01:13
3

You are dividing two integers, which will provide an integer result. In C, this means it will simply discard the fractional portion, leaving the 0.

You can cast one or both of the operands (a or b) as follows and it should clear up:

double result = (float) a / b;
adengle
  • 227
  • 1
  • 8