C:统计位数,顺序输出,逆序输出

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_41103495/article/details/83096974

统计位数,顺序输出,逆序输出

问题1.给出一个不多于5位数的正整数,要求:
(1)求出它是几位数;
(2)分别输出每一位数字;
(3)按逆序输出各位数字,例:123,输出321。

分析问题:(1)统计n是几位数字;

                  (2)分别按顺序输出每位数字 ;

                  (3)逆序输出每位数字。

解决问题:为了可以对多个数字进行分析,则先写出每个功能的函数,即自定义函数Count,PrintOrder,PrintReverse,然后从main函数中通过调用函数,从而进行测试多组数据,代码如下:

#include <stdio.h>

int Count(int n)//统计n是几位数字
{
	int temp = 0;
	do
	{
		n /= 10;
		temp ++;
	}while(n != 0);

	return temp;
}

void PrintOrder(int n)//分别输出每个数字
{
	int c = Count(n);
	int power = 1;
	for(int i = 1;i <= c - 1 ;i ++)
	{
		power *= 10;
	}
	do
	{
		printf("%d ",n / power);
		n %= power;
		power /= 10;
	}while(n != 0);
	printf("\n");
}

void PrintReverse(int n)//逆序输出每个数字
{
	int temp = 0;
	do
	{
		printf("%d ",n % 10);
		n /= 10;
	}while(n != 0);
		printf("\n");
}

int main ()
{
	printf("%d\n",Count(0));
	PrintOrder(0);
	PrintReverse(0);

	printf("%d\n",Count(12345));
	PrintOrder(12345);
	PrintReverse(12345);

	printf("%d\n",Count(9876));
	PrintOrder(9876);
	PrintReverse(9876);

	return 0;
}
--------------------- 
作者:毕宿五_ 
来源:CSDN 
原文:https://blog.csdn.net/qq_41103495/article/details/83051541?utm_source=copy 
版权声明:本文为博主原创文章,转载请附上博文链接!

编译如下:(对0,12345,9876进行测试) 

                                 

猜你喜欢

转载自blog.csdn.net/qq_41103495/article/details/83096974
今日推荐