0
int i = 5;
int j = 3;
int k;
double a, b;

k = j / 2 * i / 10;
a = 0.1 * i * j / 2.0;
b = 0.1 * (j / i) + 3.0;

So by doing it by hand one would get k=0.75, a=0.75, and b=3.06. Yet when I solve it in Visual Studio I get 0, 0.75, and 3.00. I was hoping someone could shed light on this. I know int means only whole values can be output but why is b = 3.00 rather than 3.06 since b is a double?

DanielRossi
  • 67
  • 3
  • 13
  • 1
    Possible duplicate of [What is the behavior of integer division in C?](http://stackoverflow.com/questions/3602827/what-is-the-behavior-of-integer-division-in-c) – n. m. could be an AI Feb 24 '16 at 06:12

4 Answers4

2

All of your variables should be double because if they are int integer operation will occur and your result will not contain decimal places.

double i = 5;
double j = 3;
double k;
double a, b;

k = j / 2 * i / 10;
a = 0.1 * i * j / 2.0;
b = 0.1 * (j / i) + 3.0;
Jude
  • 545
  • 3
  • 20
1

In your code,

  • i and j are of type int
  • the integer constants used here are also of type int,

So, in case of

k = j / 2 * i / 10;

integer division / multiplication will take place and the final result will be promoted to type double. This is not what you want.

either

  • use double for i and j
  • use casting to enforce floating point operation.

Same for the (j / i) part in below case.

b = 0.1 * (j / i) + 3.0;

OTOH, in case of

a = 0.1 * i * j / 2.0;

gives correct output, as the constant 0.1 or 2.0 denotes a double type, and because of the usual arithmetic conversion of the operands, floating point division / multiplication is performed.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
1

Operators for basic data types returns the strongest type of its two operands.

(j / i) is a division of integral data types, because i and j are of type int. Since i is initialized by 5 and j is initialized by 3 the result type of the division is int and the result value is 0.

Either you adapt your code like this to get the reusult you expected:

b = 0.1 * ((double)j / i) + 3.0;
                 //  ^ this is now a floating point division

Or like this:

b = 0.1 * j / i + 3.0;

Note the type of the result of 0.1 * j is of type double because 0.1 is of type double.

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
1

since j and i are integers, j/i will result in integer 0.

Integer division only gives the quotient and the remainder is discarded. E.g 10/4 equals to 2

Lincoln Cheng
  • 2,263
  • 1
  • 11
  • 17