[Resolvido] Erro de cálculo

1 resposta
ingoguilherme
Alguém sabe explicar por que isso está ocorrendo? Está dando resultados diferentes, somente o primeiro sysout mostrou o valor correto.
int boundX = (int) ( (widthFase  - (widthTiles  * 27) ) / 2);
int boundY = (int) ( (heightFase - (heightTiles * 11) ) / 2);
System.out.println(boundY + " = (" + heightFase + " - " + (heightTiles * 11) + ") / 2");

for(int i = 0; i < 27; i++){
	for(int j = 0; j < 11; j++){		
		Image imgT1 = tk.getImage(getClass().getResource("Images/chao.png"));
		
		Tile T1 = new Tile(imgT1, false, "Ground", 0, widthTiles, heightTiles, boundX, boundY);
		T1.setBounds(boundX, boundY, widthTiles, heightTiles);
		this.add(T1);
		mapa[i][j] = T1;
		
		boundY = boundY + heightTiles; 
	}
	boundY = (int) (heightFase - ((heightTiles * 11) / 2));
	boundX = boundX + widthTiles;
	
	System.out.println(boundY + " = (" + heightFase + " - " + (heightTiles * 11) + ") / 2");
}
Saída no console:
0 = (341 - 341) / 2 171 = (341 - 341) / 2 171 = (341 - 341) / 2 171 = (341 - 341) / 2 171 = (341 - 341) / 2 171 = (341 - 341) / 2 171 = (341 - 341) / 2 171 = (341 - 341) / 2 171 = (341 - 341) / 2 171 = (341 - 341) / 2 171 = (341 - 341) / 2 171 = (341 - 341) / 2 171 = (341 - 341) / 2 171 = (341 - 341) / 2 171 = (341 - 341) / 2 171 = (341 - 341) / 2 171 = (341 - 341) / 2 171 = (341 - 341) / 2 171 = (341 - 341) / 2 171 = (341 - 341) / 2 171 = (341 - 341) / 2 171 = (341 - 341) / 2 171 = (341 - 341) / 2 171 = (341 - 341) / 2 171 = (341 - 341) / 2 171 = (341 - 341) / 2 171 = (341 - 341) / 2 171 = (341 - 341) / 2
Não sei porque, mas quanto tirei os parênteses e o cast da equação, ela retornou o resultado correto, vai ver deixar passar algum detalhe, afinal quando se há muitos parênteses é fácil se confundir um pouco. Código corrigido abaixo:
int boundX = (widthFase  - (widthTiles  * 27) ) / 2;
int boundY = (heightFase - (heightTiles * 11) ) / 2;

for(int i = 0; i < 27; i++){
	for(int j = 0; j < 11; j++){		
		Image imgT1 = tk.getImage(getClass().getResource("Images/chao.png"));
		
		Tile T1 = new Tile(imgT1, false, "Ground", 0, widthTiles, heightTiles, boundX, boundY);
		T1.setBounds(boundX, boundY, widthTiles, heightTiles);
		this.add(T1);
		mapa[i][j] = T1;
		
		boundY = boundY + heightTiles; 
	}
	boundY = (heightFase - (heightTiles * 11)) / 2;
	boundX = boundX + widthTiles;
}

1 Resposta

pmlm

O que tu pensas que estavas a fazer - Multiplica, subtrai, divide:

boundY = (heightFase - (heightTiles * 11)) / 2;

O que tu realmente estavas a fazer - Multiplica, divide, subtrai:

boundY = heightFase - ((heightTiles * 11) / 2);
Criado 18 de novembro de 2014
Ultima resposta 19 de nov. de 2014
Respostas 1
Participantes 2