給出不多於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 = 0 n= 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 2013
執行結果如下圖
(有各種情況的測試!負數的順序輸出若想只有第一位數帶符號可以加上
if (n < 0)
{
printf("-");
n = -n;
}
)