c++编程 输入一个四位正整数,然后分别显示其千位数、百位数、十位数和个位数及其他每位数字对应的ASCII码

输入一个四位正整数,然后分别显示其千位数、百位数、十位数和个位数及其他每位数字对应的ASCII码。如果输入为7592,则要求输出为:
7 5 9 2
55 53 57 50

简单方法:
char a[10] = {0};
scanf("%s", a);//以字符串形式输入
assert(strlen(a)==4);//这句可以不要
printf("%c %c %c %c\n",a[0],a[1],a[2],a[3]);//以字符形式输出
printf("%d %d %d %d\n",a[0],a[1],a[2],a[3]);//以ASCLL码形式输出
温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-03-11
#include "math.h"
#include <iostream>
using namespace std;
#define M 4
void main()
{
int num,p[M],i;
cout<<"输入num(num为"<<M<<"位数的正整数):";
cin>>num;
while(num<(int)pow(10,M-1)||num>=(int)pow(10,M))
{
cout<<"输入错误!num为"<<M<<"位数的正整数。请重新输入:";
cin>>num;
}
for(i=0;i<M;i++)
{
p[i]=num/(int)pow(10,M-1-i);
num=num%(int)pow(10,M-1-i);
cout<<" "<<p[i];
}
cout<<endl;
for(i=0;i<M;i++)cout<<" "<<p[i]+48;
cout<<endl;
}本回答被提问者采纳
第2个回答  2011-03-11
#include <stdio.h>

//统计数有几位
int CountBit(int num)
{
int n = 1;
while( (num /= 10) != 0 )//如果自身除以10后 =0 说明位数计算完毕,否则再进行下次计算
{
n++;//每次位数+1,来统计位数
}
return n;
}

//按位输出 数 并显示 ASCll码
void show(int a,int n)
{
int temp=1;
n -= 1;
while(n>0)
{
temp *= 10;
n--;
}
while( a!=0 )
{
//输出int值 ,ASCLL码,把int数强制转化为char,则是按ASCLL码来的,把字符按int输出则是ASCll码了
printf( "数值:%3d ASCLL码:%3d",a/temp,(char)(a/temp) );
a %= temp; //取出 剩下的位数
temp /= 10 ; //让下次可以正确取位
}
}

int main()
{
int a = 7592;
int n;//统计位数
n=CountBit(a);//计算a的位数
show(a,n);//显示结果
}

不管你是几位数(不超int最大位数),都可以灵活转化输出。
复制到本地即可调试,编码问题有好多都看不清楚。
第3个回答  2011-03-11
将数字转化为字符,在%d输出。
func(int num)
{
int qw,bw,sw,gw;
qw = num/1000;
bw = num/100 - 10*qw;
sw = num.10 - 10*bw - 100*qw;
gw = num%10;
printf("%d %d %d %d\n",qw,bw,sw,gw);
qw1 = char(qw);
bw1 = char(bw);
sw1 = char(sw);
gw1 = char(gw);
printf("%d %d %d %d\n",qw,bw,sw,gw);
}