在我的程序中,我从文本文件中加载了一些自定义变量以供使用。
public int[] getGameSettings() {
String[] rawGame = new String[100];
String[] gameSettingsString = new String[6];
int[] gameSettings = new int[6];
int finalLine = 0;
int reading = 0;
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("gameSettings.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
//Read File Line By Line
int line = 0;
while ((strLine = br.readLine()) != null) {
// Store it
rawGame[line] = strLine;
line++;
}
//Close the input stream
in.close();
reading = line;
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
for (int a = 0; a < reading; a++) {
if (!rawGame[a].substring(0,1).equals("/")) {
gameSettingsString[finalLine] = rawGame[a];
finalLine++;
}
}
for (int b = 0; b < finalLine; b++) {
gameSettings[b] = Integer.parseInt(gameSettingsString[b]);
}
return gameSettings;
}
我从另一个类调用该方法,并将数组保存为gamessettings,然后执行以下操作:
contestedMovementPercent = (gameSettings[1]/100);
有争议的移动总是显示为0.0,即使我打印gameSettings[1],它也会显示出它应该是什么。contestedMovementPercent是一个double类型。gamessettings在这两个类中都是int数组。
我需要做某种类型的选角吗?我认为int可以这样使用
你除以的是一个整型,所以它首先将其计算为整型,然后将其转换为双精度型。将其更改为gameSettings[1]/100.0
将计算为双精度。
您可以这样做:
contestedMovementPercent = gameSettings[1] / 100.0;
使用浮点数作为除数,整型在除数前自动转换为浮点数
两个整型在赋值给双精度型之前会被强制转换为整型。int只能是整数,所以在这种情况下,要么是0,要么是1。
正如在其他答案中提到的,将任何一方设置为双精度将使除法的结果为双精度(因此gamessettings[1]/100.0)。