0

In cpp, two double value in input 2.0 and4.0 but i need answer 6.0 but i get 6.why?

#include<iostream> using namespace std; int main() { double a=2.0,b=4.0,sum; sum=a+b; cout<<sum; }

14th May 2021, 4:32 AM
Abhishek Kumar
Abhishek Kumar - avatar
3 ответов
+ 4
hey Abhishek Kumar We can print float numbers with fixed number of decimal places using std::fixed and std::setprecision, these are the manipulators, which are defined in the iomanip header file. cout<<fixed<<std::setprecision(1)<<sum;
14th May 2021, 4:50 AM
Giriraj Yalpalwar
Giriraj Yalpalwar - avatar
+ 4
As the sum of 2.0 and 4.0 doesn't really have a decimal part, C++ only displays 6. To display the decimal part also, use the 'std::showpoint' manipulator. Like so `cout << showpoint << a + b;` Note that the 'showpoint' manipulator will be turned on for the rest of the program till you turn it off. So if you do ``` double a = 2.0, b = 4.0; cout << showpoint; cout << a; // decimals displayed cout << b; // decimals displayed ``` To turn it off, use the 'noshowpoint' manipulator More info here https://www.cplusplus.com/reference/ios/showpoint/ EDIT: When you use 'showpoint', the decimal part is displayed with multiple 0s, not a single 0. You can use the std::setprecision manipulator in the <iomanip> header file to limit the precision to 1 decimal point https://www.cplusplus.com/reference/iomanip/setprecision/
14th May 2021, 4:55 AM
XXX
XXX - avatar
+ 2
You can see this : #include <iostream> #include<iomanip> using namespace std; int main() { double a = 2.0, b = 2.0,sum; sum = a + b; cout << showpoint; cout << fixed; cout << setprecision(1); cout << sum; return 0; }
14th May 2021, 4:55 AM
1AmN0t0k@eArth