【C语言】求所输入整数的位数、逆序数

给一个不多于5位的正整数,要求:
1、求出它是几位数;
2、分别输出每一位数字
3、按逆序输出各位数字,例如原数为321,应输出123;

#include <stdio.h>              //包含标准库的信息
#include <math.h>               //<math.h> 头文件中声明了一些数学函数和宏
int main(void)                  //每个程序都从main函数的起点开始执行
{
    int num,indiv,ten,hundred,thousand,ten_thousand,place;//数,个,十,百,千,万,位数
    printf("请输入一个整数(0-99999)");
    scanf("%d",&num);
    if(num >9999)//大于9999且小于99999的数自然是5位数
        place = 5;
    else if (num >999)
        place = 4;
    else if (num > 99)
        place = 3;
    else if (num > 9)
        place = 2;
    else place = 1;
    printf("位数:%d\n",place);
    printf("每位数字为:");
    ten_thousand = num/10000;//取万
    thousand = (int)(num - ten_thousand * 10000)/1000;//把万减了,int是向下取整,得千位
    hundred = (int)(num - ten_thousand * 10000 - thousand * 1000)/100;//同理
    ten=(int)(num - ten_thousand * 10000 - thousand * 1000 - hundred * 100)/10;//同理
    indiv=(int)(num - ten_thousand * 10000 - thousand * 1000 - hundred * 100 - ten * 10);//同理
    switch (place)
    {
        case 5:
            printf("%d,%d,%d,%d,%d",ten_thousand,thousand,hundred,ten,indiv);//把每位数显示出来
            printf("\n反序数字为:");
            printf("%d%d%d%d%d\n",indiv,ten,hundred,thousand,ten_thousand);//重新组合为倒序数
            break;
        case 4:
            printf("%d,%d,%d,%d",thousand,hundred,ten,indiv);
            printf("\n反序数字为:");
            printf("%d%d%d%d\n",indiv,ten,hundred,thousand);
            break;
        case 3:
            printf("%d,%d,%d",hundred,ten,indiv);
            printf("\n反序数字为:");
            printf("%d%d%d\n",indiv,ten,hundred);
            break;
        case 2:
            printf("%d,%d",ten,indiv);
            printf("\n反序数字为:");
            printf("%d%d\n",indiv,ten);
            break;
        case 1:
            printf("%d",indiv);
            printf("\n反序数字为:");
            printf("%d\n",indiv);
            break;
    }
    return 0;
}

运行结果
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_42294351/article/details/107280205