我的主要问题涉及printf()的使用和格式化说明符。我有一个包含整数的100个元素的数组,大多数当前初始化为零。我想将内容以10x10格式转储到屏幕上,格式如下:
0 1 2 3 4 5 ...
0 +0000 +0000 +0000 +0000 +0000 +0000
1 +0000 +0000 ...
2 ...
3
...
使用我当前的代码,我的格式有点偏离 -
0 1 2 3 4 5 6 7 8 9
+1103 +4309 +1234 +0000 +0000 +0000 +0000 +0000 +0000 +0000
0 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000
1 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000
2 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000
3 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000
4 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000
5 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000
6 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000
7 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000
8 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000
9
当前(相关)代码:
void dump (int *dumpMemory, int SIZE) {
int i = 0;
for (i; i < 10; ++i) { // Output 1-10 at top row of dump
printf("\t%d", i);
}
puts("");
for (i = 0; i < SIZE; i++) {
printf("\t%+05d", dumpMemory[i]);
if ((i % 10) == 9) {
printf("\n%d", (i / 10));
}
}
puts("");
}
左侧索引已向下移动一个点,因此在打印到屏幕时未正确表示其位置。
答案 0 :(得分:0)
这主要是在正确的地方打印东西的问题。标题线很好。在i % 10 == 0
时打印条目之前,您需要打印行前缀;在i % 10 == 9
时打印条目后,您需要打印换行符;在循环之后,如果i % 10 != 0
,则需要打印换行符以终止数字行。然后,可以选择是否添加另一个以在转储后放置一个空行。
void dump(int *data, int size)
{
for (int i = 0; i < 10; ++i) // Output headings 0..9
printf("\t%d", i);
putchar('\n');
for (int i = 0; i < size; i++)
{
if (i % 10 == 0)
printf("%d", i / 10); // Consider outputting i?
printf("\t%+05d", data[i]);
if (i % 10 == 9)
putchar('\n');
}
if (size % 10 != 0)
putchar('\n'); // Finish current/partial line
putchar('\n'); // Optional blank line
}