两种方法
-
#include<stdio.h>
-
int main(){
-
int n = 123456;
-
int unitPlace = n / 1 % 10;
-
int tenPlace = n / 10 % 10;
-
int hundredPlace = n / 100 % 10;
-
int thousandPlace = n / 1000 % 10;
-
printf("个位:%d\n十位:%d\n百位:%d\n千位:%d\n", unitPlace, tenPlace, hundredPlace, thousandPlace);
-
getchar();
-
return 0;
-
}
-
#include <stdio.h>
int main(void)
{
unsigned int number = 0;
unsigned int single_digit = 0;
unsigned int ten_digit = 0;
unsigned int hundreds_digit = 0;
unsigned int thousands_digit = 0;
scanf("%d", &number);
thousands_digit = number / 1000;
hundreds_digit = number % 1000 / 100;
ten_digit = number % 1000 % 100 / 10;
single_digit = number % 1000 % 100 % 10;
printf("%d, %d, %d, %d\n", thousands_digit, hundreds_digit, ten_digit, single_digit);
return 0;
}n/10是为了将数字n的小数点移到5和6之间,123456变成12345.6,由于int型只保留整数,所以结果只会留下“12345”。由于我们用的是十进制,任意一个十进制数字的十位、百位、千位等都由10的整数倍构成,所以理所当然也可以被10整除,所以任意一个数%10,剩下的只有个位。
补充:如果想同时取出个位和十位,可以直接对123456%100,这样会剩下56。 -
对第二种方法的解释