gpt4 book ai didi

c++ - 如何在单个 cout 中对多个变量进行 set.precision

转载 作者:行者123 更新时间:2023-11-28 00:06:43 25 4
gpt4 key购买 nike

我主要有这个:

Product newProduct;
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
newProduct.display();

在 Product.cpp 中我有:

cout << "$" << basePrice << " - " 
<< name << " - " << cout.precision(1) << weight << " lbs\n";

但是在 .cpp 中将精度更改为 (1) 也会将 basePrice 更改为 (1)。如何更改同一 cout 中不同变量的精度?有办法吗?还是我只是将它们放在不同的 cout 中?那行得通吗?为什么或者为什么不?

更新当我尝试第二个 cout 时,它会将数字 2 添加到我的 name 变量的末尾。换句话说,我在 name 变量之后结束了第一个 cout。它正在运行,但将数字 2 添加到末尾。

最佳答案

使用 std::setprecision 操纵器代替:

cout << setprecision(2) << "$" << basePrice << " - " 
<< name << " - " << setprecision(1) << weight << " lbs\n";

号码2cout.precision()的返回值函数,它是当前精度值,被插入到流中并因此输出。

编辑:

哎呀,忘了加#include <iomanip> .

编辑 2:

有关完整性,请参阅 this question我的为什么cout.precision()在中间调用时会影响整个流。

关于c++ - 如何在单个 cout 中对多个变量进行 set.precision,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35284876/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com