Find the number of digits in the number, and output the digits in sequence and reverse order

Given a positive integer with no more than 5 digits, request:
1. Find out how many digits it is;
2. Output each digit separately;
3. Output each digit in reverse order, for example, the original number is 321, and 123 should be output.

code show as below

#include<stdio.h>
#include<math.h>
int Count(int long long n)//求一个整数的位数
{
    
    
	int temp = 0;//初始化一个值
	if(n == 0)
	{
    
    
		return 1;//返回1,说明是一位数字0
	}
	while(n != 0)
	{
    
    
		temp++;//每进一次循环,多一位
		n /= 10;//n除10减一位数后,再将n赋值成除后的值
	}
	return temp;
}
void PrintReverse(int long long n)//从个位输出每一位数字,得到个位,再丢弃个位
{
    
    
	if(n < 0)//判断数字是正数还是负数,将输出值变成正值
	{
    
    
		printf("-");
		n = -n;
	}
	do
	{
    
    
		printf("%d",n%10);//对10取余数,输出个位数字
		n /= 10;// 丢弃个位,保留未输出的位
	}while(n != 0);//循环执行条件n不等于0
	printf("\n");
}
void PrintOrder(int long long n)
{
    
    
	if(n < 0)//正数输出
	{
    
    
		printf("-");
		n = -n;
	}
	if(n == 0)
	{
    
    
		printf("0\n");
		return ;//退出本函数
	}
	int temp = Count(n);//求这个数字的位数
	int power = (int)pow(10.0,temp-1);
	/*pow(x,y),计算x的y次方,x,y都是double型,所以把10改为10.0。temp-1意思是比最高位少一位*/
	while(n != 0)
	{
    
    
		printf("%d",n/power);//输出最高位。举例如1234/100,的到最高位1
		n %= power;//丢弃最高位。举例如1234%100,得到234
		power /= 10;//一次循环后减一位
	}
	printf("\n");
}
int main()
{
    
    
	printf("输入的数字为123456789\n");
	printf("输入的正数的位数为:%d\n",Count(123456789));
	printf("将输入的整数的位数从个位逐个输出:\n");
	PrintReverse(123456789);
	printf("将输入的整数从最高位逆序输出:\n");
	PrintOrder(123456789);
	return 0;
}

The result is as follows
The result is clear and correct

Guess you like

Origin blog.csdn.net/MDakuya/article/details/102637779