如何确定数字的位数并确定要运行的循环数?
例如,如果我有一个数组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)
Run Code Online (Sandbox Code Playgroud)
这是我的代码,但是当它遇到整数之间的零时失败...
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;
}
}
Run Code Online (Sandbox Code Playgroud)
Bri*_*ian 10
您可以使用对数.
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);
}
Run Code Online (Sandbox Code Playgroud)