Could some please explain why this code is outputting 1 when it should be 1.5;

#include <iostream>
using namespace std;
int main()
{
    double a = 3/2;
    cout << a;
}

thanks

3 and 2 are integers (in C++, they have the 'int' type), so the division sign in 3/2 refers to integer division, which produces an int return value, which must be truncated. If you write 3.0/2 or 3/2.0, one of the values will be a double, thus forcing the other value to autoconvert to a double. Then you'll get floating point division, which will give you 1.5, or an approximation of 1.5.

Thank you

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.