【问题标题】:Using setprecision on and off使用 setprecision 打开和关闭
【发布时间】:2015-09-13 16:52:49
【问题描述】:

堆栈溢出和 C++ 的新手

std::cout << std::fixed << "Starting Balance: $" << std::setprecision(2) << startbal << endl;
    std::cout<< "Annual Interest Rate: " << intrestrate << endl;
    std::cout << std::fixed << "Monthly Payment: $" << std::setprecision(2) <<monthlypay << endl;

我在这里尝试从我拥有的数组中打印,它的打印大部分是正确的,但我需要第二行不受 setprecision 的影响,这样年利率就不会改变。

打印后我得到:

    Starting Balance: $1000.00
    Annual Interest Rate: 0.05
    Monthly Payment: $120.00

但我需要它来停止将年利率四舍五入,因为它应该是 0.055。感谢您提前提供任何帮助!

【问题讨论】:

标签: c++


【解决方案1】:

所以记住当前的精度,改变它,然后恢复原来的精度。
在类似这样的代码中:

auto const   precBefore  = std::cout.precision();
std::cout << std::setprecision(digitsAfterDecimalCount) << val;
std::cout << std::setprecision(precBefore);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多