来源谭c语言switch和if应用的一个很好的例子!(没想到自己比谭教授写的还精简一些)特来分享一下!

abc罗大侠 2016-03-23 12:05:49
题目:给一个不多于5位数的正整数,要求:
1.求出它是几位数;
2.分别输出每一位数;
3.按逆序输出各位数字。


#include<stdio.h>
int main()
{
int x,indiv,t,h,th,t_th,place;
scanf("%d",&x);
if(x>99999)
printf("It is error.\n");
else if(x>9999)
place=5;
else if(x>999)
place=4;
else if(x>99)
place=3;
else if(x>9)
place=2;
else if(x>=0)
place=1;
else
printf("It is error.\n");//如题按步进行编码,先完成(1)的要求。

t_th=x/10000;
th=(x-t_th*10000)/1000;
h=(x-t_th*10000-th*1000)/100;
t=(x-t_th*10000-th*1000-h*100)/10;
indiv=(x-t_th*10000-th*1000-h*100-t*10);//谭教授的方法



/*indiv=x%10;
t=x/10%10;
h=x/100%10;
th=x/1000%10;
t_th=x/10000;//我的方法*/



switch(place)
{case 1 : printf("它是1位数%d\n",indiv);
break;
case 2 : printf("第2位数是%d\n第1位数是%d\n",t,indiv);
printf("反序数字为");
printf("%d%d\n",indiv,t);
break;
case 3 : printf("第3位数是%d\n第2位数是%d\n第1位数是%d\n",h,t,indiv);
printf("反序数字为");
printf("%d%d%d\n",indiv,t,h);
break;
case 4 : printf("第4位数是%d\n第3位数是%d\n第2位数是%d\n第1位数是%d\n",th,h,t,indiv);
printf("反序数字为");
printf("%d%d%d%d\n",indiv,t,h,th);
break;
case 5 : printf("第5位数是%d\n第4位数是%d\n第3位数是%d\n第2位数是%d\n第1位数是%d\n",t_th,th,h,t,indiv);
printf("反序数字为");
printf("%d%d%d%d%d\n",indiv,t,h,th,t_th);
break;
}//进行第2、3步
return 0;
}



#include<stdio.h>
int main()
{
int x=54321,indiv,t,h,th,t_th;
indiv=x%10;
t=x/10%10;
h=x/100%10;
th=x/1000%10;
t_th=x/10000;
printf("第5位数是%d\n第4位数是%d\n第3位数是%d\n第2位数是%d\n第1位数是%d\n",t_th,th,h,t,indiv);
printf("反序数字为");
printf("%d%d%d%d%d\n",indiv,t,h,th,t_th);
return 0;
}



#include<stdio.h>
int main()
{
int x=54321,indiv,t,h,th,t_th;
t_th=x/10000;
th=(x-t_th*10000)/1000;
h=(x-t_th*10000-th*1000)/100;
t=(x-t_th*10000-th*1000-h*100)/10;
indiv=(x-t_th*10000-th*1000-h*100-t*10);
printf("第5位数是%d\n第4位数是%d\n第3位数是%d\n第2位数是%d\n第1位数是%d\n",t_th,th,h,t,indiv);
printf("反序数字为");
printf("%d%d%d%d%d\n",indiv,t,h,th,t_th);
return 0;
}

以上就是全部部分,我都只用54321试验过,新手水平有限,有什么错误,麻烦指出,谢谢!!!!!!!!!!!!!!!
...全文
297 8 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
赵4老师 2016-03-24
  • 打赏
  • 举报
回复
4楼的代码好靓!
小灸舞 版主 2016-03-23
  • 打赏
  • 举报
回复
encoderlee 2016-03-23
  • 打赏
  • 举报
回复
wang0635 2016-03-23
  • 打赏
  • 举报
回复
谭的代码好丑
ooolinux 2016-03-23
  • 打赏
  • 举报
回复
不错,多思考,书上的很多例子可以优化和改进,也可以添加新的功能。
abc罗大侠 2016-03-23
  • 打赏
  • 举报
回复
嗯嗯,学到了,但是谭c的这道题在前面,还没讲到数组。
赵4老师 2016-03-23
  • 打赏
  • 举报
回复
#include<stdio.h>
int main() {
    int x,L,i;
    char s[6];
    scanf("%d",&x);
    if(x<0 || 99999<x) {
        printf("0<=x<=99999\n");
        return 1;
    }
    L=sprintf(s,"%d",x);
    printf("它是%d位数\n",L);
    for (i=0;i<L;i++) printf("第%d位数是%c\n",i+1,s[i]);
    printf("反序数字为");
    for (i=L-1;i>=0;i--) printf("%c",s[i]);
    printf("\n");
    return 0;
}
abc罗大侠 2016-03-23
  • 打赏
  • 举报
回复
第一次发有技术性的帖子,感谢!

70,020

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧