我有一堆 int 值,例如 10, 5, 4, 2, 1。我有一堆 Double
List<Double>
中的值比如 0.65 等等
我如何通过这个列表检查每个 Double 最接近哪个 int 值?
我的代码是针对 Android 音乐应用程序的。这是我最终解决这个问题的方法。
@Override
public void onClick(View v) {
String[] noteNames = new String[9];
double[] notes = new double[9];
double crotchet = 60.0 / Long.parseLong(setBPM.getText().toString());
double quaver = crotchet / 2.0;
double tripletQuaver = crotchet / 3.0;
double dottedCrotchet = crotchet + quaver;
double semiquaver = quaver / 2.0;
double dottedQuaver = quaver + semiquaver;
double minum = crotchet * 2.0;
double dottedMinum = minum + crotchet;
double semibreve = minum * 2.0;
notes[0] = semiquaver;
notes[1] = tripletQuaver;
notes[2] = quaver;
notes[3] = dottedQuaver;
notes[4] = crotchet;
notes[5] = dottedCrotchet;
notes[6] = minum;
notes[7] = dottedMinum;
notes[8] = semibreve;
noteNames[0] = "semiquaver";
noteNames[1] = "tripletQuaver";
noteNames[2] = "quaver";
noteNames[3] = "dottedQuaver";
noteNames[4] = "crotchet";
noteNames[5] = "dottedCrotchet";
noteNames[6] = "minum";
noteNames[7] = "dottedMinum";
noteNames[8] = "semibreve";
for(double l : notes) {
System.out.println(l);
}
double[] tempCurrentDiff = new double[9];
double[] currentDiff = new double[9];
for (Double d : beats) {
for (int i = 0; i < 9; i++) {
currentDiff[i] = Math.abs(notes[i] - d);
tempCurrentDiff[i] = Math.abs(notes[i] - d);
}
Arrays.sort(tempCurrentDiff);
for (int i = 0; i < 9; i++){
if (currentDiff[i] == tempCurrentDiff[0]) {
System.out.println(noteNames[i]);
notesView.append(noteNames[i] + " ");
break;
}
}
}
}
最佳答案
使用Math.round(double)
函数对列表中的每个元素进行四舍五入。 Math.round(double)
返回参数的最接近 long
,并向上舍入 ties(0.5
)。但是,如果参数为 NaN
,则结果为 0
。
所以,
- 使用
Arrays.sort(a)
对给定的整数数组int[] a
进行排序(如果尚未排序) - 浏览列表中的每个双
x
- 查找整数
key = Math.round(x)
- 使用
Arrays.binarySearch(a, key)
;其中a
是包含整数数组元素的int[]
。如果数组a
中不存在该元素,则此函数可能会返回负索引
。负索引:(-(插入点) - 1)。
代表我们正在搜索的数组的插入点。
示例代码:
double doub[] = {0.5, 2.6, 3.7, 1.7, 4.6};
long a[] = {1, 4, 3}; //
Arrays.sort(a);
for(double x : doub)
{
long key = Math.round(x);
int index = Arrays.binarySearch(a, key);
if(index < 0) // element wasn't found
index = - index -1;
if(index > a.length -1) // key is greater than the maximum element
index = a.length - 1;
System.out.println("double: "+x+" rounded key: "+key+" value: "+a[index]);
}
关于java - Java 中最接近 Double 的 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19828966/