'\t' 字符 space 数组中相同 printf() 函数的差异

'\t' character space differance in same printf() function in array

我在 windows 8.1 中编写了此 C 代码并在 GNU GCC 和 TURBO C 编译器中编译。该代码具有大小为 20 的浮点数组,并使用 for 循环打印数组,并将“\t”字符放入 printf() 函数中以用于间隔目的。 在 20 次的整个循环中,'\t' 应该打印等于 spaces 但它只打印 2 space 用于 a[i] 0 到 10 的值和 regualr space 在剩余执行。 我不明白为什么会这样。是不是打印float变量后用的?

代码C代码如下图:

#define n 20

    int main()
    {
        float a[n]={0.1,0.9,0.23,0.8,0.32,0.57,0.4,0.14,0.25,0.11,0.7,0.86,0.75,0.19,                    0.55,0.95,0.34,0.29,0.64,0.45},ex,temp,x;
        int i,idx;
        system("cls");

        /*for(i=0 ; i<n ; i++)
        {
            printf("a[%d]: %f\t",i,a[i]);
        }*/

        for(i=0 ; i<n ; i++)
        {
            x=a[i];
            idx=a[i]*10;

            printf("\na[%d]: %f \t idx: %d",i,a[i],idx);
            //printf("\na[%d]: %f *\t idx: %d",i,a[i],idx);
        }

        getch();
        return 0;
    }

O/p的图片如下:

根据图像中显示的 o/p,红线区域中的 space 小于蓝线区域。这怎么可能?是什么原因呢?


'\t' 是 TAB 的转义序列。
然后 TAB "moves the active position to the next horizontal tabulation position on the current line"。
因此,它不会打印等距,而是将光标移动到当前行的下一个制表位置。

\t 只是一个字符。你的终端将决定如何处理它,通常它意味着 "move on to the next tab stop position",一个常见的约定是每 8 列有一个这样的位置。您无法在您的程序中控制您的终端将如何处理它。

如果您想控制输出格式,请改用 printf() 提供的功能。转换允许指定字段宽度和精度,使用它们,请参见此处的示例:http://www.cprogramming.com/tutorial/printf-format-strings.html

您可能混淆了 tab-space 和 padding。 Tab-space(假设值为 8)在屏幕上的 6 个字符后将留下 2 个字符的 space,而在 8 个字符后将连续 8 space 留空。填充允许我们将打印在屏幕上的数据按需要对齐。您的问题的可能(和临时)解决方案是:删除 printf 语句中 /t 之后的 space 。希望有用