在 C 中使用 '\r' 替换 for 循环中的数字

Using '\r' to replace a number in for loop in C

我需要一个 for 循环计数器,当它可以被一组数字整除时,它应该用文本替换数字。我已经有了循环和代码,但我的 printf 函数中的 '\r' 对其他人的编译器不起作用。

这是我的代码和不同编译器的输出,因此您可以更好地识别问题。

#include <stdio.h>

void hey(void)
{
    
    for (int i = 50; i <= 100; i++)
    {
        printf("%d", i);

        if (i % 5 == 0)
        {

            printf("\rHEY1 ");
        }
        if (i % 40 == 0)
        {

            printf("\rHEY2 ");
        }
        if (i % 40 == 0 && i % 5 == 0)
        {

            printf("\rHEY3 ");
        }

        printf("\n");
    }
}

int main(void)
{
    hey();
    return 0;
}

这是我的编译器的结果,这正是我想要的:

My output

这是我老师用来标记的在线编译器上的样子:

Other output

出于某种原因,它不会删除要在其他编译器中替换为 'Hey' 的数字。相反,将其打印在新行上。

我该如何解决这个问题?它应该删除数字并打印字母而不是第一个屏幕截图上的字母。 TIA.

我怀疑你的老师不希望你使用'\r',而是希望你首先弄清楚如何不输出数字,而是立即打印“嘿”。这在所有环境中都是可靠的。

她就是你如何做到的。请注意,我使用了 else if 并且我重新排序了支票,以便获得我确定是您想要的情况 80.
我还简化了 80 条件,因为重新排序允许这样做。
我为 80 选择了“HEY3”选项。您永远不会在此代码的输出中找到“HEY2”和“HEY3”,因为任何能被 40 整除的东西也总是能被 5 整除。


#include <stdio.h>

void hey(void)
{
    
    for (int i = 50; i <= 100; i++)
    {
        if (i % 40 == 0 /* && i % 5 == 0 */)
        {

            printf("HEY3 ");
        } else if (i % 5 == 0)
        {

            printf("HEY1 ");
        } /* else if (i % 40 == 0)
        {
            printf("HEY2 ");
        } */ else  
        {
            printf("%d", i);
        }

        printf("\n");
    }
}

int main(void)
{
    hey();
    return 0;
}

输出:

HEY1 
51
52
53
54
HEY1 
56
57
58
59
HEY1 
61
62
63
64
HEY1 
66
67
68
69
HEY1 
71
72
73
74
HEY1 
76
77
78
79
HEY3 
81
82
83
84
HEY1 
86
87
88
89
HEY1 
91
92
93
94
HEY1 
96
97
98
99
HEY1