求(0~99999)整数的位数和逆序的两种方法(while和switch)

目录

  1. while语句(循环结构)
  2. switch语句(多分支选择结构)

一、while循环结构

程序………………

#include<stdio.h>
int main()
{
	int m,n,w,nx=0,i=0;     // w:位数  nx:逆序 
 	printf("请输入一个0~99999之间的整数m:");
	scanf("%d",&m);   //58743
	n=m;
	if(n%10==0)
        i++;
	while(n!=0)
	{                 //一    二    三   四    五 
	    w=n%10;       //3     4     7    8     5
		i++;          //1     2     3    4     5      (位数) 
		nx=nx*10+w;   //3     34    347  3478  34785  (逆序 )
		n=n/10;	      //5874  587   58   5     0
	}
	printf("位数:%d\n",i);
	printf("逆序:%d\n",nx);
	return 0;
}

执行结果………………

在这里插入图片描述

二、switch多分支选择结构

程序………………

#include<stdio.h>
int main()
{
	int num,g,s,b,q,w,place;    //用拼音首字母表示整数各位名称 
	printf("输入一个0~99999的正整数 m=");
	scanf("%d",&num);
	if(num>9999)
	    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("每位数字为:");
    w=num/10000;        //万位 
    q=(num/1000)%10;    //千位 
    b=(num/100)%10;     //百位 
    s=(num/10)%10;      //十位 
    g=num%10;           //个位 
	switch(place)
	{
	case 5:printf("%d,%d,%d,%d,%d",w,q,b,s,g);   // place=5 
	       printf("\n反序数字为:");
	       printf("%d %d %d %d %d\n",g,s,b,q,w);
		   break;
    case 4:printf("%d,%d,%d,%d",q,b,s,g);      // place=4 
	       printf("\n反序数字为:");
	       printf("%d %d %d %d\n",g,s,b,q);
		   break;
	case 3:printf("%d,%d,%d",b,s,g);       // place=3
	       printf("\n反序数字为:");
	       printf("%d %d %d\n",g,s,b);
		   break;
	case 2:printf("%d,%d",s,g);         // place=2
	       printf("\n反序数字为:");
	       printf("%d %d\n",g,s);
		   break;
	case 1:printf("%d",g);             // place=1
	       printf("\n反序数字为:");
	       printf("%d\n",g);
		   break;
	} 
	return 0;
}

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

发布了25 篇原创文章 · 获赞 54 · 访问量 892

猜你喜欢

转载自blog.csdn.net/weixin_46022083/article/details/105298900