0
#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.

  • 1
    What is "_double form_"? Can you give an example of what you now get and what you expect to get instead? – Ted Lyngmo May 20 '21 at 08:29
  • What are you expecting and how is it coming? – Wander3r May 20 '21 at 08:30
  • Use: `std::setprecision:` – Mike May 20 '21 at 08:31
  • My guess is that OP means this: [Where and How to format a C++ code to 2 decimal places](https://stackoverflow.com/questions/18564555/where-and-how-to-format-a-c-code-to-2-decimal-places#18564574). They want result in form `5.0`, but the output is `5`. – Yksisarvinen May 20 '21 at 08:31
  • when I enter 4.0 the output is coming 8 – Nitin Kumar May 20 '21 at 08:39
  • Tip: when writing examples like this, don't prompt for input. Just put the values that show the problem directly into the code. That makes it much easier for readers to see what's happening. You'd see the same output with `double d = 4, b = 4, e; e = b + d; std::cout << e << std::endl;`. – Pete Becker May 20 '21 at 12:15

1 Answers1

1

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

Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69