整数取十百千位

两种方法
  1. #include<stdio.h>

  2. int main(){

  3. int n = 123456;

  4. int unitPlace = n / 1 % 10;

  5. int tenPlace = n / 10 % 10;

  6. int hundredPlace = n / 100 % 10;

  7. int thousandPlace = n / 1000 % 10;

  8. printf("个位:%d\n十位:%d\n百位:%d\n千位:%d\n", unitPlace, tenPlace, hundredPlace, thousandPlace);

  9. getchar();

  10. return 0;

  11. }

  12. #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。

  13. 对第二种方法的解释

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值