提问人:Zeptuz 提问时间:12/11/2022 最后编辑:Zeptuz 更新时间:12/11/2022 访问量:46
我似乎无法使用 setprecision c++ [closed] 正确计算小数的数量
I cant seem to get the amount of decimals right using setprecision c++ [closed]
问:
我目前正在研究子程序/子程序或任何你用英语称呼它们的东西,在我试图解决的这个特定任务中,我必须计算两个单词的平均长度。
void Length(string const text_1,
string const text_2,
int & total_length,
double & mean_length)
{
total_length = text_1.length() + text_2.length();
mean_length = static_cast<double>(total_length) / 2;
}
void Length_Program(int val)
{
string text_1;
string text_2;
int total_length{};
double mean_length{};
cout << "Mata in två ord: ";
cin >> text_1 >> text_2;
cout << "Totallängd: ";
Length(text_1, text_2, total_length, mean_length);
cout << total_length << endl;
cout << "Medellängd: " << fixed << setprecision(1) << mean_length;
}
我已将精度设置为 setprecision(1),我假设它只会写一个小数,但我不断得到两个小数。 我的例子是:abcd E 它应该说它是平均 2.5 个单词,但出于某种原因它说 2.51。有人可以帮我了解我做错了什么吗?
答:
6赞
Mark Ransom
12/11/2022
#1
您的问题是您忘记了最后一行输出。操作系统显示的返回代码将追加到输出中。工作正常。<< endl
setprecision
评论
0赞
Zeptuz
12/11/2022
伙计,我讨厌错过这些小东西,非常感谢!
评论
1
<< '\n'
mean_length