-2

In one problem I am receiving such inputs and I need to output them as it is.
For example I will receive 5.0 as input and need to print 5.0 as output,
but it is printing 5. I used setprecision which is not working .
I think the thing is for numbers like 2.0,3.0,4.0 it is rounding off while taking input itself. Please help me.

See my code:

float n=5.0

//  n*=1.0;
cin>>n;
cout<<setprecision(16);
cout<<n;//its printing 5 here 

/*
I also tried
printf("%f",n);
//but its printing 5.000000
I can't use printf("%.1f",n)<br>
as input can be 5.234 or 4.5687 so making %.1f will not work for others


*/
Rahul Sinha
  • 1,969
  • 14
  • 17
  • 2
    What's the difference between `5`, `5.0`, `5.00`, `5.000`? Mathematically, nothing at all. How should it know which you want? Do you specifically mean you always want 1 decimal place? It seems not. Do you want all non-`0` decimal places? Doesn't seem to be that either. (And this is before we even get into the issue of differing binary and decimal representations). If you want exactly what the user typed, maybe you really want a `std::string`? – BoBTFish Jun 08 '16 at 08:48
  • Use `setw(4)` additionally. – πάντα ῥεῖ Jun 08 '16 at 08:50
  • Use `std::fixed` together. – songyuanyao Jun 08 '16 at 08:53
  • @BoBTFish this was in a online judge problem.. so we need to output as asked, clearly 5 and 5.0 are not different mathematically but if i will print it so the judge will give wrong answer. So i was hoping for a solution other than using string – user6439179 Jun 08 '16 at 10:04
  • @DieterLücking please go through the problem its different than [link]http://stackoverflow.com/questions/17341870/correct-use-of-stdcout-precision-not-printing-trailing-zeros Correct use of std::cout.precision() - not printing trailing zeros problem – user6439179 Jun 08 '16 at 10:07

1 Answers1

1

You can use std::fixed. This will, like printf do, force to print all the precision decimals. This means that 5 is now printed 5.000000, if you don't mind more than one unneeded 0.

If you do mind, I don't see many solutions, but to write the string in memory with an ostringstream or with sprintf, then to append ".0" if you cannot find a point in it, and to print that string.

Lærne
  • 3,010
  • 1
  • 22
  • 33