习题 3.12 给出一个不多于5位的正整数,要求:1. 求出它是几位数;2. 分别打印出每一位数字;3. 按逆序打印出各位数字,例如原数位321,应输出123。
代码:
#include<iostream>
using namespace std;
int main()
{
int x;
int p,w,n; //p做指示器,w存储位数
cout << "please input a number(<10000) :" << endl;
cin >> x;
if (x >= 10000)
{
cout << "Error!" << endl;
return 0;
}
if (x != 0)
{
for (p = 1, w = 0; (x / p) != 0; p *= 10)
{
++w;
}
cout << "此数的位数为:" << w << endl;
n = p; //n存储最大的位数
cout << "顺序输出为:" << endl;
for (p /= 10; p != 0; p /= 10)
{
cout << (x / p) % 10 << endl;
}
cout << endl;
cout << "逆序输出为:" << endl;
for (p = 1; p != n; p *= 10)
{
cout << (x % (p * 10) / p) << endl; //灵活运用%和/符号
}
}
else
{
cout << "此数的位数为:" << 1 << endl;
cout << "顺序输出为:" << 0 <<endl;
cout << "逆序输出为:" << 0 <<endl;
}
return 0;
}