设置精度C ++ [英] Setting up precision C++
问题描述
因此,我正在尝试为代码中的输入值设置精度.我不希望精确地将数值打印出来,但要精确到小数点后两位小数.
So, i'm attempting to set the precision for input values in my code. I want the values to be printed with two decimal points afterwards of precision though i'm not exactly sure how.
这是我的代码.
#include <iostream>
#include <iomanip>
float uphill, wellD, waterLvl, buckVol;
float buckAscRate, downHill, volume;
float last;
float timeReq;
int scene = 1;
void timeRequired()
{
std::setw(2);
std::setprecision(2);
std::cout << "Scenario " << scene << ":" << std::endl;
std::cout << "up hill" << " " << uphill << " sec" << std::endl;
std::cout << "well diamter" << " " << wellD << " in" << std::endl;
std::cout << "water level" << " " << waterLvl << " in" << std::endl;
std::cout << "bucket volume" << " " << buckVol << " cu ft" << std::endl;
std::cout << "bucket ascent rate" << " " << buckAscRate << " in/sec" << std::endl;
std::cout << "down hill" << " " << downHill << " sec" << std::endl;
std::cout << "required volume" << " " << volume << " cu ft" << std::endl;
timeReq = (uphill + downHill);
std::cout << "TIME REQUIRED" << " " << timeReq << " sec" << std::endl;
std::cout << " " << std::endl;
}
void scenarioCONT()
{
do
{
std::cin >> wellD;
std::cin >> waterLvl;
std::cin >> buckVol;
std::cin >> buckAscRate;
std::cin >> downHill;
std::cin >> volume;
std::cin >> last;
if (uphill <= 1) uphill = 2;
if (wellD <= 0) wellD = 1;
if (waterLvl <= 0) waterLvl = 1;
if (buckVol <= 0) buckVol = 1;
if (buckAscRate <= 0) buckAscRate = 1;
if (downHill <= 0) buckAscRate = 1;
if (volume <= 0) volume = 1;
if (last > 1)
{
uphill = last;
scenarioCONT();
}
} while (last != 0);
}
void scenario()
{
do
{
std::cin >> uphill;
std::cin >> wellD;
std::cin >> waterLvl;
std::cin >> buckVol;
std::cin >> buckAscRate;
std::cin >> downHill;
std::cin >> volume;
std::cin >> last;
if (uphill <= 1) uphill = 2;
if (wellD <= 0) wellD = 1;
if (waterLvl <= 0) waterLvl = 1;
if (buckVol <= 0) buckVol = 1;
if (buckAscRate <= 0) buckAscRate = 1;
if (downHill <= 0) buckAscRate = 1;
if (volume <= 0) volume = 1;
if (last > 1)
{
timeRequired();
uphill = last;
scenarioCONT();
}
scene++;
timeRequired();
} while (last != 0);
}
int main()
{
scenario();
system("pause");
}
有人告诉我要用ionmanip来设置精度,尽管我不是100%做到这一点.有什么建议吗?
I've been told to use ionmanip to set the precision, though i'm not 100% on how to do it. Any suggestions?
推荐答案
如果要输出2个十进制数字,则应将std::fixed
和std::setprecision()
一起使用.
If you want to output 2 decimal digits, you should use std::fixed
, together with std::setprecision()
.
此处.
为便于理解,下面是一个示例:
cout << setprecision(2)<< 3.1415;
输出3.1
(总共2位数字)和
For easier understanding, here is an example:
cout << setprecision(2)<< 3.1415;
outputs 3.1
(2 digits in total) and
cout << setprecision(2)<<fixed<< 3.1415;
输出3.14
(浮点后2位)
这篇关于设置精度C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!