c - while循环递增和递减

标签 c

我正在尝试根据 1-9 范围内的单个用户输入来增加和减少值。
例如。如果用户输入 5,程序输出 1234'5'4321。所以目标是让它从 1 递增到输入的数字,然后从输入的数字递减到 1。
我目前能够递增和递减,但它递减到 0 而不是 1,然后它会产生一个我不希望它产生的错误。目标是使用 while 循环创建它,我怀疑我的错误是从我的第二个嵌套 while 循环中产生的,但我不确定如何解决它。我尝试将条件更改为“num > 0”,逻辑上递减应以 1 结束,但这并不能解决问题

while(num != 0 && num <= 9){
        while(i != num){
            i++;
            printf("%d", i);
        }
            while(num != 0){
                num--;
                printf("%d", num);
        }

    }
    printf("Error: Number exceeds range!\n");

最佳答案

这是因为你先将num递减,然后打印出来。

num = 1 时,它进入循环并递减到 0 从而打印 0

if (num != 0 && num <= 9){
        while(i < (num-1)){
            i++;
            printf("%d", i);
        }

        while(num != 0){
           printf("%d", num);
           num--;
        }
    }

此外,对于外部条件,您不需要,您需要的是if

关于c - while循环递增和递减,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54342739/

相关文章:

c - 写入/dev/mem 失败,地址错误

c - 如何使用 settimeofday(2)?

c - 在 C 中检索上次引导时间戳

c - 尝试从 LZMA SDK 编译 LzmaUtil.c

c - 如何将字符的值传递给c中的另一个.bat文件?

c - GCC 内联汇编错误 : "Operand size mismatch for ' int'"

c++ - 将 char 指针中的字符替换为 memmove

c - 为什么 argc 作为参数传递给 main,而我们实际上并没有传递它?

c - 如何动态分配 'typedef struct' 元素的数组?

c - 发送源地址为 0.0.0.0 的 UDP 包