c - C语言的数字输出

标签 c

大家好,我是编码初学者,我试图弄清楚如何输出所有数字。例如数字 158 中的数字 1,5,8,15,58,158。抱歉英语不好。

我尝试过一些方法,但它并不适用于所有数字,而且我相信一定有更好的方法来编码它而无需所有 while 循环。

    #include <stdio.h>

int main(){
    long num = 5025;
    int num1=num ,num2= num, num3=num;
   
    while(num1 !=0)
    {
        int digit = num1 % 10;
        num1 = num1/10;
        printf("%d\n", digit);
    } 
    while(num2 >10)
    {
        
        int digit = num2 % 100;
        
        num2 = num2 / 10;
                
        printf("%.2d\n", digit);
    }
    while(num3 >100)
    {
        
        int digit = num3 % 1000;
        
        num3 = num3 / 10;
                
        printf("%.3d\n", digit);
    }
    
    return 0;
}

最佳答案

我的看法是,没有字符串并且复杂性稍低。如果数字有 0 位,它将打印右侧数字的重复项。

#include <stdio.h>

int main(void)
{
    int digits[64]; // size of array must cover however many digits are in long max
    int numDigits = 0;
    long num = 15876;

    // populate array with each digit
    while (num)
    {
        digits[numDigits++] = num % 10;
        num /= 10;
    }

    // start at the end of the array (since digits are loaded in it backwards)
    for (int first=numDigits-1; first>=0; first--)
    {
        int temp = digits[first];
        printf("%d\n", temp);  // print the initial condition
        for (int last=first-1; last>=0; last--)
        {
            // continue to build temp by multiplying by 10 and adding the next digit
            temp = (temp * 10) + digits[last];
            // could easily put the output in a comma-separated list if that's needed
            printf("%d\n", temp);
        }
    }
}

输出

1
15
158
1587
15876
5
58
587
5876
8
87
876
7
76
6

Demo

关于c - C语言的数字输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69890299/

相关文章:

c - 如何访问指针数组中的指针指向的值?

c - Windows中的 `fprintf()`和 `fscanf()`是否需要以文本模式打开文件

c - 如何在不使用递归和层序遍历的情况下求二叉树的高度?

无法从链表末尾删除节点

c - 系统函数的返回值

c - MPI 2x 打印

c - 相对于调用它的源文件映射宏

c - 从H264规范中如何理解这一行

python - 如何同时将 Python 与 C 和 Java 结合使用?

c++ - 为什么在 C 中允许对 int * arr[] 进行以下赋值?