所以,我试图在代码中设置输入值的精度。我希望这些值以后以两个小数点的精度打印,尽管我不确定如何。
这是我的代码。
#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%的方法。有任何建议吗?
您可以使用std::setprecision
函数。以下示例直接从http://www.cplusplus.com/reference/iomanip/setprecision/
double f =3.14159;
std::cout << std::setprecision(5) << f << 'n';
std::cout << std::setprecision(9) << f << 'n';
如果要输出2个小数位数,则应将std::fixed
与std::setprecision()
一起使用。
在这里看看。
为了更轻松地理解,这是一个示例: cout << setprecision(2)<< 3.1415;
输出3.1
(总计2位数字)和
cout << setprecision(2)<<fixed<< 3.1415;
输出3.14
(浮点后2位数字)