我在访问数组中的值时遇到问题,目的是从我试图获得最接近匹配的值中减去数组第 1 列中保存的值。我收到类型不匹配错误无法从 double 转换为 int
顺便说一句,我什至确定我是否以正确的方式解决问题。我有一张表,我在其中检查第 1 列中的值是否与我正在查找的值最接近,而该行中的其他列是需要返回的值。(如果你玩过的话,想想有点像 AD&D 中的一些桌子)
// Column 1 ability score, 2 Damage mod, 3 Lift , 4 carry, 5 drag
double arr [][] = {{1.01,-7,11,9,28},
{1.51,-6,25,12,63},
{2.01,-6,38,14,96},
{2.51,-5,51,14,96},
{3.01,-5,51,17,128}};
public double EXTcha(double cha) {
double closestNo = 0;
double lookingFor = cha;
int reqIndex = 0;
double i;
for (int row=0; row < arr.length; row++) {
System.out.println(row+"row \t");
double currentDiff = (lookingFor-arr[i][0]);
System.out.println(currentDiff+"diff \t");
if (currentDiff < closestNo) {
closestNo = currentDiff;
System.out.println(closestNo+"closest \t");
reqIndex = row;
};
}
for (int column=0; column<arr[reqIndex].length;column++) {
System.out.println(arr[reqIndex][column]+"\t");
}
return extcha;
}
这是进行建议更改后其他人的代码
// Column 1 ability score, 2 Damage mod, 3 Lift , 4 carry, 5 drag
double arr [][] = {{1.01,-7,11,9,28},
{1.51,-6,25,12,63},
{2.01,-6,38,14,96},
{2.51,-5,51,14,96},
{3.01,-5,51,17,128}};
public double EXTcha(double cha) {
double closestNo = 50;
double lookingFor = cha;
int reqIndex = 0;
for (int row=0; row < arr.length; row++) {
System.out.println(row+"row \t");
double currentDiff = Math.abs(lookingFor-arr[row][0]);
System.out.println(currentDiff+"diff \t");
if (currentDiff < closestNo){
closestNo = currentDiff;
System.out.println(closestNo+"closest \t");
reqIndex = row;
};
}
for (int column=0; column<arr[reqIndex].length;column++) {
System.out.println(arr[reqIndex][column]+"\t");
}
return extcha;
}
我遇到了另一个初始化closestNo
为 0 的问题,这意味着当我对它进行测试时(currentDiff < closestNo)
总是小于所以我将它设置为 50,它总是大于第 1 列中的双精度值。
我希望这可以帮助某人