gpt4 book ai didi

c++ - CPP Setfill() 在 for 循环的第二步和其他步骤中重复自身

转载 作者:太空狗 更新时间:2023-10-29 20:52:04 24 4
gpt4 key购买 nike

一个简单的 C++ 乘法表。

int main() {
int i, j; i = j = 1;
for (i; i < 10; i++) {
for (j = 1; j < 10; j++)
cout << setw(3) << i*j;
cout << endl << setw(3) << setfill('x');
}
}

输出是:

  1  2  3  4  5  6  7  8  9
xx2xx4xx6xx8x10x12x14x16x18
xx3xx6xx9x12x15x18x21x24x27
xx4xx8x12x16x20x24x28x32x36
xx5x10x15x20x25x30x35x40x45
xx6x12x18x24x30x36x42x48x54
xx7x14x21x28x35x42x49x56x63
xx8x16x24x32x40x48x56x64x72
xx9x18x27x36x45x54x63x72x81

但我期待的是:

  1  2  3  4  5  6  7  8  9
xx2 4 6 8 10 12 14 16 18
xx3 6 9 12 15 18 21 24 27
xx4 8 12 16 20 24 28 32 36
xx5 10 15 20 25 30 35 40 45
xx6 12 18 24 30 36 42 48 54
xx7 14 21 28 35 42 49 56 63
xx8 16 24 32 40 48 56 64 72
xx9 18 27 36 45 54 63 72 81

我在这里错过了什么?谢谢。

最佳答案

std::setfill is a "sticky" manipulator : 它将改变 ostream 的状态,直到它被还原。

如果在打印第一个数字后还原它,您将得到预期的输出:

for (i; i < 10; i++) {
for (j = 1; j < 10; j++)
cout << setw(3) << i*j << setfill(' ');
cout << endl << setw(3) << setfill('x');
}

live example on wandbox.org

关于c++ - CPP Setfill() 在 for 循环的第二步和其他步骤中重复自身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47238137/

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