Search code examples
c++coding-style

why is my output not coming in double form, when everything that i've declared is in double form?


#include <iostream>

using namespace std;

int main()
{

    double d = 4, b, e;

    cin >> b;
    e = b + d;

    cout <<e<< endl;
}

why is my output not coming in double form, when everything I've declared is double? I've already tried typecasting it, but still, it's not working as I want it to work. When I give 4.0 as input, it gives 8 as output but I want it to give 8.0 as the output.


Solution

  • There is no double form. Printing necessitate a format, a specification of the way the result is outputted, whatever you print.

    ostreams does have an internal states to decide the way a given argument is printed. Basically, these can be controlled through input/output manipulators. There is some that can be applied to control floating-point output.

    Non exhaustive list:

    • std::showpoint (noshowpoint) to printed (or not) the decimal point.

    • std::fixed, std::scientific, std::hexfloat, std::defaultfloat to choose in between several common notations.

    • std::setprecision(int n) to choose how many decimal digits will appear.

    Default precision is 6.

    By default (if you don't set correct state), if your double value (say 8.0 or 8.5) can be printed shortly it will, thus 8 (or 8.5).

    See : https://en.cppreference.com/w/cpp/io/manip/setprecision and https://en.cppreference.com/w/cpp/io/manip/fixed