+ 4

Double sum problem in output, C++, HELP

Hello. I have the code bellow where I have a double variable and I get another from user input. I can't understand why do I get a result in form of "10" instead of "10.0" in the console output. Without declaring another variable for their sum. Please help! ______________________________________________________ #include <iostream> using namespace std; int main() { int i = 4; double d = 4.0; string s = "I can't understand why do I get 8 instead of 8.0 in the output for d+d2 "; int i2; double d2; string s2; cin>>i2; // i2=12; cin>>d2; // d2=4.0; cin>>s2; // s2="Sleeping is my SUPERPOWER!"; cout<<i+i2<<endl; cout<<d+d2<<endl; cout<<s+s2<<endl; return 0; }

27th Mar 2017, 6:40 AM
Elena
Elena - avatar
2 odpowiedzi
+ 7
Because the extra ".0" is redundant information. If you want to make it visible, include the <iomanip> header, and then use std::setprecision(2) followed by std::fixed to always show 2 decimal places: std::cout << std::setprecision(2) << std::fixed << d + d2 << std::endl; "setprecision" sets the minimum number of decimal places to show, and "fixed" forces it to always show that many decimal places, even if it's just 0.
27th Mar 2017, 6:48 AM
Squidy
Squidy - avatar
+ 4
Thank you very much :) Sometimes there are these details I struggle with
27th Mar 2017, 7:10 AM
Elena
Elena - avatar