Department in C ++

I am new to C ++ and I have tried this simple code:

#include<iostream>
#include<math.h>
using namespace std;

int main(){
    double a;
    a=1/6;
    cout<<a;
}

But the result is 0. As I understand it, double should work with real numbers, so the result should not be 1/6 or 0.1666666? Thank!

+4
source share
2 answers

In the expression, 1 / 6both numbers are integers. This means that this division will perform integer division, which leads to 0. To perform the separation double, one number must be double: 1.0 / 6for example.

+5
source

Integer literals 1and 6are of type int. So in the expression

1/6

integer arithmetic is used, and the result is 0.

.

a = 1.0/6;

a = 1/6.0;

a = 1.0/6.0;
+2

All Articles