8

I am new to C++ and I 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 understood, double should work with real numbers, so shouldn't the result be 1/6 or 0.1666666? Thank you!

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Silviu
  • 749
  • 3
  • 7
  • 17
  • 3
    It's not `double` *when you perform the division*, it's `int`. It becames `double` later, when you assign it to double. Use `1.0/6.0`, it will work as you want. Also, `1.0/6` and `1/6.0` will work. – HolyBlackCat Mar 28 '16 at 16:24
  • 2
    Hence you are new: Do not get accustomed to `using namespace std;` ! –  Mar 28 '16 at 16:25
  • 1
    Also, use the c++ standard headers, therefore, use `#include `. – ranu Mar 28 '16 at 16:31

2 Answers2

10

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

Rakete1111
  • 47,013
  • 16
  • 123
  • 162
6

Integer literals 1 and 6 have type int. Thus in the expression

1/6

there is used the integer arithmetic and the result is equal to 0.

Use at least one of the operands as a floating literal. For example

a = 1.0/6;

or

a = 1/6.0;

or

a = 1.0/6.0;
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 1
    Does this means that C++ makes implicit casting? Would be nice to add this information in your answer. – ranu Mar 28 '16 at 16:32
  • @RafaelCamposNunes The compiler needs to determine the common type of the operands and of the result. It ises the usual arithmetic conversions of the operands converting integer types to float types if one of the operands is of floating type. – Vlad from Moscow Mar 28 '16 at 16:40