c - 逆序/正序输出每位.

时间:2023-03-08 16:26:04
 #include <stdio.h>
#include <math.h> /*
判断一个正整数的位数,并按正序,逆序输出他们的位.
*/ int
invert(int); void
order(int, int); int
main(void) {
int n = ;
printf("original:%d\n", n);
int bitCont = invert(n);
printf("\nbits: %d\n", bitCont);
order(n, bitCont);
return ;
} //逆序输出每一位并记录位数.
int
invert(int n) {
int bitCount = ; //记录位数.
do
{
++bitCount;
printf("%d ", n % ); //逆序输出每一位.
n /= ;
} while (n); //终止条件是"n为0".
return bitCount;
} //正序输出每一位.
void
order(int n, int bitCount) {
int tmp = ; //存储即将减去的级别,如当n为"1234"时,存储"1000";当n为"234"时,存储"100".
int h = ; //存储最高位的位.
while(n) {
tmp = (int)pow((double), --bitCount);
h = n / tmp;
printf("%d ", h);
n -= h * tmp;
}
}

output:

original:56789
9 8 7 6 5
bits: 5
5 6 7 8 9 请按任意键继续. . .
 //二,使用(求余数方法)
void
count_vMod(int input) {
//分别表示'个位,十位,百位,千位,万位'上的数字.
int one, ten, hundred, thousand, ten_thousand; ten_thousand = input / ; //除1万.
thousand = input % / ; //取余1万后除1千.
hundred = input % / ; //取余1千后除1百.
ten = input % / ; //取余1百后除1十.
one = input % ; if(ten_thousand)
printf("共有5位数,%d %d %d %d %d\n", one, ten, hundred, thousand, ten_thousand);
else if(!ten_thousand && thousand)
printf("共有4位数,%d %d %d %d\n", one, ten, hundred, thousand);
else if(!ten_thousand && !thousand && hundred)
printf("共有3位数,%d %d %d\n", one, ten, hundred);
else if(!ten_thousand && !thousand && !hundred && ten)
printf("共有2位数,%d %d\n", one, ten);
else if(!ten_thousand && !thousand && !hundred && !ten && one)
printf("共有1位数,%d\n", one);
}

虽然第二中方法(求余数)在求某位数的时候,有用,但是感觉比较笨拙(主要是对这个题目,特别是if判断时).