setting precision
I am starting out here with a simple temperature conversion program from F to C. I would like the C temperature to round to the 1/10 decimal place. I have 5 temperature conversions and can manually set the precision for 开发者_开发问答each. But perhaps this is not a best practice?
The Fahrenheit temperature for location 0 is 55 and to get a Celsius temperature of 12.8 I had to use setprecision(3).
cout<<"location 1 = "<<location1f<<" F "<<setprecision(3)<<location01<<" C \n";
For this second location the Fahrenheit temperature was 44 and the resulting C temp was only 1 digit left of the decimal, so I had to change the precision to 2.
cout<<"location 2 = "<<location2f<<" F "<<setprecision(2)<<location2c<<" C \n";
I am using double as my variable type. Instead of going through and changing the precision for the expected answer, what is the best way to output the C temperature to a single decimal place?
The setprecision
manipulator behaves differently depending on which mode you happen to be in. The default mode causes it to set the total number of digits displayed. If you set the display mode to fixed
then precision
to 1, it will always display one digit after the decimal point.
std::cout << std::fixed << std::setprecision(1) << value;
printf("My temperature is %2.1f\n", temperature)
精彩评论