Why does the output shows 8 instead of 8.0 | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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

12th Jul 2020, 8:03 AM
Naman Kapoor
Naman Kapoor - avatar
3 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
12th Jul 2020, 10:20 AM
Jayakrishna 🇮🇳
+ 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;}
12th Jul 2020, 10:20 AM
Arya
0
Thanks, everyone, problem solved,
12th Jul 2020, 12:20 PM
Naman Kapoor
Naman Kapoor - avatar