0

I was solving a question and suddenly amazed to know that we are getting 2 as output, however the output should be something like 2.000000.

#include <iostream>
using namespace std;   
int main()
{
    double a = 6 / 4;
    int b  = 6 / 4;
    double c = a + b;
    cout << c;
}

Why the output is 2? Why there are no decimal values in the answer.

Carbon
  • 97
  • 1
  • 3
  • 2
    since `c` is round integer, `cout` automatically output it as an integer. I think this is what you are looking for: https://stackoverflow.com/questions/5907031/printing-the-correct-number-of-decimal-points-with-cout – 440 May 17 '22 at 14:42
  • I've seen this assumption some times before. But what's the difference between `2` and `2.0` and `2.00` and `2.000`? They are different string representations of _exactly the same_ number. I think @Sedenion 's link is the better duplicate here. – churill May 17 '22 at 14:49
  • 1
    `6 / 4` An `int` divided by an `int` will give you an `int`. Assigning the answer to a `double` variable is too late -- the damage has already been done. – PaulMcKenzie May 17 '22 at 14:57
  • @PaulMcKenzie But 'a' being a double data type should store 1.000000, not just 1. – Carbon May 17 '22 at 15:03
  • @Carbon -- `a` stores the floating-point value 1. The output shows the value with no decimal parts because it's exactly an integer value. Read about [`std::showpoint`](https://en.cppreference.com/w/cpp/io/manip/showpoint). – Pete Becker May 17 '22 at 15:09
  • @Carbon -- If you looked at `a` in a debugger, you will see that the value is `1.0000`. That is entirely different than wanting to *format* a number for display. What if I wanted to see two decimal places? Or scientific notation? – PaulMcKenzie May 17 '22 at 15:14

0 Answers0