2

I got some problems . I input a=5.999 with d=1 and expected output is 6 but its output is 6.0. I mean I want to delete .0 in my output if it had. Example: Input: a=3.864361,d=3,Output expected: 3.864/ Input:a=5.9577,d=1 Output expected: 6/ Input:
a=0.07266,d=3,Output expected:0.073.

#include <iomanip>

using namespace std;

int main()
{
    float a;
    int d;
    cin>>a>>d;
    cout<<setprecision(d)<<fixed<<a;
    return 0;
}
  • 1
    A minor detail, but why 5.999 should be 6 while 3.888 should be 3.88? – Amadeus Sep 20 '19 at 14:42
  • Interesting.. The documentation on cppreference, with examples, state that precision is how many digits, are generated. However, your testcase, and my experiments run on wandbox, show that precision controls the amount of digits, **after the decimal point**. And I am not sure who is correct. – Algirdas Preidžius Sep 20 '19 at 14:43
  • So you've got 5.999 problems and d is 1 – Lightness Races in Orbit Sep 20 '19 at 14:48
  • This is my mistake cauz my question is not clearly, With the example 5.888, I want 2 number after decimal point. But with 5.999, I want 1 number after decimal point and hope output is 6 – Ngọc Huyền Sep 20 '19 at 14:52
  • https://wandbox.org/permlink/w1b5NsmWTIVSbe3Z – Marek R Sep 20 '19 at 14:52
  • It runs on wandbox but , It doesn't run on CodeBlocks... yea .. – Ngọc Huyền Sep 20 '19 at 15:10
  • Note that meaning of precision changes depending if you are using `fixed` or `scientific` or `defaultfloat` https://wandbox.org/permlink/s2iSEvFZJVdPzIan and it must run on Code:Blocks – Marek R Sep 20 '19 at 15:43
  • @MarekR I can't build it, Codeblocks says that " defaultfloat was not declare..." though I paste all your code in codeblocks – Ngọc Huyền Sep 20 '19 at 15:59
  • `defaultfloat` is available since `c++11` you have to enable it (`-std=c++11`). – Marek R Sep 20 '19 at 16:32

1 Answers1

-1

Sadly, this is one example I know of where C++ solution is purely inferior to C. To the best of my knowledge, there is no way to do that with C++ streams.

On the other hand, C has printf format specifier exactly for that: %g

Following code will do what you want (don't forget to include stdio.h):

printf("%.1g\n", a);
SergeyA
  • 61,605
  • 5
  • 78
  • 137