如何确定数字的位数并确定要运行的循环编号?
例如,如果我有一个数组 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/