1 #include <stdio.h> 2 #include <math.h> 3 4 /* 5 判断一个正整数的位数,并按正序,逆序输出他们的位. 6 */ 7 8 int 9 invert(int); 10 11 void 12 order(int, int); 13 14 int 15 main(void) { 16 int n = 56789; 17 printf("original:%d\n", n); 18 int bitCont = invert(n); 19 printf("\nbits: %d\n", bitCont); 20 order(n, bitCont); 21 return 0; 22 } 23 24 //逆序输出每一位并记录位数. 25 int 26 invert(int n) { 27 int bitCount = 0; //记录位数. 28 do 29 { 30 ++bitCount; 31 printf("%d ", n % 10); //逆序输出每一位. 32 n /= 10; 33 } while (n); //终止条件是"n为0". 34 return bitCount; 35 } 36 37 //正序输出每一位. 38 void 39 order(int n, int bitCount) { 40 int tmp = 0; //存储即将减去的级别,如当n为"1234"时,存储"1000";当n为"234"时,存储"100". 41 int h = 0; //存储最高位的位. 42 while(n) { 43 tmp = (int)pow((double)10, --bitCount); 44 h = n / tmp; 45 printf("%d ", h); 46 n -= h * tmp; 47 } 48 }
output:
original:56789
9 8 7 6 5
bits: 5
5 6 7 8 9 请按任意键继续. . .
1 //二,使用(求余数方法) 2 void 3 count_vMod(int input) { 4 //分别表示'个位,十位,百位,千位,万位'上的数字. 5 int one, ten, hundred, thousand, ten_thousand; 6 7 ten_thousand = input / 10000; //除1万. 8 thousand = input % 10000 / 1000; //取余1万后除1千. 9 hundred = input % 1000 / 100; //取余1千后除1百. 10 ten = input % 100 / 10; //取余1百后除1十. 11 one = input % 10; 12 13 if(ten_thousand) 14 printf("共有5位数,%d %d %d %d %d\n", one, ten, hundred, thousand, ten_thousand); 15 else if(!ten_thousand && thousand) 16 printf("共有4位数,%d %d %d %d\n", one, ten, hundred, thousand); 17 else if(!ten_thousand && !thousand && hundred) 18 printf("共有3位数,%d %d %d\n", one, ten, hundred); 19 else if(!ten_thousand && !thousand && !hundred && ten) 20 printf("共有2位数,%d %d\n", one, ten); 21 else if(!ten_thousand && !thousand && !hundred && !ten && one) 22 printf("共有1位数,%d\n", one); 23 }
虽然第二中方法(求余数)在求某位数的时候,有用,但是感觉比较笨拙(主要是对这个题目,特别是if判断时).