+ 2
Why does the output shows 8 instead of 8.0
#include <iostream> #include <cstdio> using namespace std; int main() { int i = 4; float d = 4.0; string s = "HackerRank "; int a; float b; string c; cin>>a; cin>>b; cin.ignore(); getline(cin,c); cout<<a+i<<endl; cout<<(b+d)*1.0<<endl; cout<<s<<" "<<c;} When I run the given code and add input values as 12 and 4.0 then I get the output as 16 and 8 instead of 8.0 , this keeps on happening even though I am using Float/double. Kindly help
4 Answers
+ 2
c++ trims output 4.0 to 4 automatically...
If you want use precision representation methods..
fixed or setprecision(1)..
Edit:
Same question, you may get complete answer:
https://stackoverflow.com/questions/41841682/why-does-this-c-program-round-double-values-and-not-print-the-whole-string
+ 1
I think it's taking the default precision,as if you enter any value suppose 8.5, it's displaying as 12.5 but for only with input with .0 it's not displaying precision value..well try this..as it prints precision value too
#include <iostream>
#include <cstdio>
#include <iomanip>
using namespace std;
int main() {
int i = 4;
float d = 4.0;
string s = "HackerRank ";
int a;
float b;
string c;
cin>>a;
cin>>b;
cin.ignore();
getline(cin,c);
cout<<a+i<<endl;
cout<<fixed<<setprecision(1)<<(b+d)*1.0<<endl;
cout<<s<<" "<<c;}
0
Thanks, everyone, problem solved,