【问题标题】:How to extract the hundredths digit of an int [duplicate]如何提取int的百分之一[重复]
【发布时间】:2020-04-03 22:27:17
【问题描述】:

如何提取一个int变量的百位? 比如我有一个随机数:

int i = 5654217;

我想要代码提取数字“2”。

我试过了

i/100

这给了我 56542。

但我找不到只提取最后一个数字的方法。

同样,我真的不确定这是提取一百个变量的最佳方法。

【问题讨论】:

标签: java numbers extract


【解决方案1】:

我不是 100% 确定你在问什么,所以我会提出我对你的问题的两个猜测。如果它不能回答您的问题,请随时告诉我,我会帮助您。

1) 您将整数 (int) 除以 100,最后 2 位数字消失。

double x = (double)i/100.0;
//ints cannot store a decimal

2) 你有一个小数(双精度)并试图输出百位数字。

public int hundredthsDigit(double x){
    if(x>0.0) return (x/100)%10; 
    //This moves the 100s digit to the 1s digit and removes the other digits by taking mod 10
    return 10-Math.abs(x/100)%10;
    // does practically the same thing, but is a work around as mod doesn't work with negatives in java
}

【讨论】:

    【解决方案2】:

    模数运算符% 有效地为您提供除法的余数。

    你可以通过获取数字来获取最后一位数字,mod 10。试试(i / 100) % 10

    您可以在此处阅读有关模运算等的更多信息:https://en.m.wikipedia.org/wiki/Modular_arithmetic

    【讨论】:

    • 这是remainder 运算符。数字的modulus 实际上是不同的东西,对于正数可能是负数。
    • 这不适用于负数
    【解决方案3】:

    请在下面找到代码:

        package com.shree.test;
    
    public class FindNumber {
    
        public static int findNumberAt(int location,int inputNumber) {
            int number = 0;
    
            //number =  (inputNumber % (location*10))/location;    // This also works
            number =  (inputNumber/location)%10; // But as mentioned in other comments and answers, this line is perfect solution 
    
            return number;
    
        }
    
        public static void main(String[] args) {
            System.out.println(findNumberAt(100, 5654217));
        }
    }
    

    【讨论】:

    • 代码丢失并不能帮助人们学习。请解释你的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-22
    • 2018-08-20
    • 2016-06-19
    • 2018-12-24
    • 2014-02-23
    • 1970-01-01
    相关资源
    最近更新 更多