1000字范文,内容丰富有趣,学习的好帮手!
1000字范文 > 给出不多于5位的正整数 求出它是几位数 分别输出每一位按逆序输出每一位数字。

给出不多于5位的正整数 求出它是几位数 分别输出每一位按逆序输出每一位数字。

时间:2024-02-22 13:36:32

相关推荐

给出不多于5位的正整数 求出它是几位数 分别输出每一位按逆序输出每一位数字。

给出不多于5位的正整数,要求:

1,求出它是几位数

2,分别输出每一位数

3,按逆序输出每一位数字,例如原数为321,应输出123.

第一种方法:

(1)求一个数是几位数,有一种方法是:

if (x > 9999)

{

place = 5;

printf("这是一个五位数\n");

}

else if (x > 999&&x < 9999)

{

place = 4;

printf("这是一个四位数\n");

}

else if (x > 99&&x < 999)

{

place = 3;

printf("这是一个三位数\n");

}

else if (x>9&&x<99)

{

place = 2;

printf("这是一个两位数\n");

}

else if (x > 0&&x < 9)

{

place = 1;

printf("这是一个一位数\n");

}

这种方法虽然简单,但是可利用性不强,如果判断的是N位数的数字,那么要写的else if(),就不是一两个了,所以实际应用中就不太合适。

(2)分别输出每一位数字,顺序输出十进制数字n,如123 -》1 2 3

myriabit = x / 10000;//万位

thousend = (x - myriabit * 10000) / 1000;//千位

hundred = (x - myriabit * 10000 - thousend * 1000) / 100; //百位

tendigit = (x - myriabit * 10000 - thousend * 1000 - hundred * 100) / 10;// 十位

unitsdigit = (x - myriabit * 10000 - thousend * 1000 - hundred * 100 - tendigit * 10) / 1;//个位

printf("(2)个位%d,十位%d,百位%d,千位%d,万位%d\n", unitsdigit, tendigit, hundred, thousend, myriabit);// 个位

(3)按逆序输出每一位数字,例如原数为321,应输出123.

switch(place)

{

case 1:printf("(3)逆序为:%d" , unitsdigit);break;

case 2:printf("(3)逆序为:%d%d" , unitsdigit , tendigit);break;

case 3:printf("(3)逆序为:%d%d%d" , unitsdigit , tendigit , hundred);break;

case 4:printf("(3)逆序为:%d%d%d%d" , unitsdigit , tendigit , hundred , thousend);break;

case 5:printf("(3)逆序为:%d%d%d%d%d" , unitsdigit , tendigit , hundred , thousend , myriabit);break;

}

另一种方法是:

(1)求一个数是几位数,:

丢弃个位 ,例如123,

123 / 10 = 12 n = 12 count =1;

12 / 10 = 1 n =1 count =2;

1 / 10 = 0n= 0 count =3;

int GetFigures(int n)

{

int count = 0;

if(n / 10 != 0)

{

count++;

}

n /= 10;//丢弃个位

}

程序简单可利用性比上面的方法强很多,可以解决正数,负数但是0不可以。

如果要加上0,有两种解决方法:

1,在前面加上一个判断。

2,do

{

count++;

n /= 10;//丢弃个位

}while(n != 0);

(2)分别输出每一位数字,顺序输出十进制数字n,如123 -》1 2 3

void PrintOrder1(int n)

{

int count;

count = GetFigures(n);//函数调用

int power = 1;

//pow(10,count-1);

for(int i = 0; i < count - 1; i++)

{

power *= 10;//power = power * 10;

}

do

{

printf("%d ",n/power);//得到最高位

n %= power;//丢弃最高位

power /= 10;

}while(n!=0);

printf("\n");

}

还有利用栈的方法:

void PrintOrder(int n)

{

stack<int> s;

do

{

s.push(n % 10);//进栈

n /= 10;

} while (n != 0);

while (!s.empty())

{

printf("%d ", s.top());

s.pop();

}

printf("\n");

}

(3)按逆序输出每一位数字,例如原数为321,应输出123.

void PrintReverse(int n)

{

if(n < 0)

{

printf("-");

n = -n;

}

do

{

printf("%d ",n%10);//得到个位数字

n /= 10;//丢弃个位数字

}while(n!=0);

printf("\n");

下面是程序的总代码,运行环境为Visual Studio

运行结果如下图

(有各种情况的测试!负数的顺序输出若想只有第一位数带符号可以加上

if (n < 0)

{

printf("-");

n = -n;

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。