Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Division in C++ [duplicate]

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!

like image 274
Silviu Avatar asked Mar 28 '16 16:03

Silviu


2 Answers

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.

like image 101
Rakete1111 Avatar answered Sep 24 '22 02:09

Rakete1111


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;
like image 45
Vlad from Moscow Avatar answered Sep 21 '22 02:09

Vlad from Moscow