我在使用 std::fixed 时缺少什么

What is missing from my use of std::fixed?

本文关键字:什么 fixed std      更新时间:2023-10-16

我正在编写一个程序来模拟plinko板,在该程序中,我有一个输出分配给每个插槽的资金的函数。我正在尝试使用 std::fixed 和 std::setprecision 输出每个小数点后有两个零的值,但每个值都输出,就好像我根本没有使用 fixed 一样。我错过了什么?这是我的代码:

#include <iostream>
#include <iomanip>
using namespace std;
void ChipsAllSlots(int numChips) {
    const int NUM_SLOTS = 9;
    const int slotWinnings[NUM_SLOTS] = {100, 500, 1000, 0, 10000, 0, 1000, 500, 100};
    for (int i = 0; i < numChips; ++i) {
        cout << fixed << setprecision(2) << slotWinnings[i] << endl;
    }
}
int main() {
    ChipsAllSlots(9);
    return 0;
}

std::fixedstd::setprecision只影响浮点数的输出。你输出整数,所以这些操纵器不起作用。如果在插入流之前转换为浮点数,或者首先使用浮点数组,则会看到缺少.00