Basic variable assignment question

Hello,

I have a very basic question that I don't understand why. For following code:
1
2
const int n=4;
double inis=1/n;

I thought the value of inis should be 0.25 by assignment with expression. However, when I run it, inis=0.
Could someone please tell me why?
When doing division of two integers in C++ the result will be an integer. If you don't want that should make sure that at least one of the operands are a floating point number.

1
2
const int n=4;
double inis=1.0/n;
The value "1" is be default an integer. The value n is an integer. The operation (1/n) performs integer division, which truncates remainders. The result, which should be 0, will be stored in the double variable inis, so it is casted to double value before being stored.

To get the division operation for doubles, at least one of the operands must be a double. You can cast either one (for instance 1/(double)n or 1/double(n)), or you can declare 1 to be a constant of type double (1.0/n)
OK I get it! Thank you for your explanation!
Topic archived. No new replies allowed.