java - 如何在 Java 中获取数字的 'place'(例如十位、千位等)

标签 java

如何确定数字的位数并确定要运行的循环编号?

例如,如果我有一个数组 int[] a= {123,342,122,333,9909}int max = a.getMax() 我们得到值 9909。我想要获取 9909 的数字位值,即第千位。

例如...

(number place value,number of loop to run)

(one,1 time)
(tenth,2 time)
(hundred,3 time)
(thousand,4 time)
(ten thousand,5 time)
(hundred thousand,6 time)

这是我的代码,但是当它遇到整数之间的零时会失败...

public static int getMax(int[] t,int n){
     int maximum = t[0];   // first value of the array
     int index = 0;
     int div=1;
     int numSpace=0;
     int valueTester=34;
     boolean done=false;

     for (int i=1; i<n; i++) {
       if (t[i] > maximum) {
         maximum = t[i];   // maximum
         index = i; // comparing index
       }  
     }

     while(done==false){
         if (valueTester==0){
             done=true;
             }
          else{
            valueTester=(maximum / div) % 10;
            div=div*10;
            numSpace++;
            }
        }

     return numSpace;
     }

  }

最佳答案

您可以使用对数。

    double[] values = {4, 77, 234, 4563, 13467, 635789};
    for(int i = 0; i < values.length; i++)
    {
        double tenthPower = Math.floor(Math.log10(values[i]));
        double place = Math.pow(10, tenthPower);
        System.out.println(place);
    }        

关于java - 如何在 Java 中获取数字的 'place'(例如十位、千位等),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9962420/

相关文章:

java - 在 JButton 的中心画一个圆

java - 如何将 Java Deque<T> 转换为 DefaultListModel?

Java Mapreduce 排序复合值

java - 如何导入多行csv文件?

java - 如何知道线程需要完成的确切时间

java - 输入流返回 NullPointerException (Java)

java - 将抽象类存储在数组列表中

java - wsgen 'Class not found'

java - Spring Boot JUnit Jackson 无法反序列化所有字段

java - jaxb 中的 Map<String, MyObject>