Pourquoi le ce arithmétique égal à 10 et pas 0 avec un mod en java
Question
Je travaille sur un ancien examen pour un test et ce code imprime la valeur de 10 pour Longvariable.Maintenant, à la main, pour moi, les maths iraient 9 + 1% 10= reste de 0, pas 10 ... Comment suis-je tort sur cela?
Merci d'avoir aidé!
public class ExamSectionA
{
public static void main(String[] args)
{
int intVariable1 = 9;
int intVariable2 = 10;
double doubleVariable = 11.2;
char charVariable = 'A';
long longVariable;
longVariable = intVariable1 + 1 % intVariable2;
intVariable2 = (int) (doubleVariable / 10f);
String[] theirSalary = {"10","20","30","40"};
System.out.println(intVariable2);
System.out.println(longVariable);
}
}
EDIT: PEMDAS.Pense que je l'ai eu.
La solution
Watch your order of operations:
intVariable1 + 1 % intVariable2;
is:
intVariable1 + (1 % intVariable2);
So 9 + 1 % 10
is being parsed as 9 + (1 % 10)
. Which gives 9 + 1 = 10
.
%
has higher precedence than +
.
Autres conseils
% operator has higher priority than +. For more information go here
Corrected code: (intVariable1 + 1) % intVariable2;
Did you mean instead (9+1) % 10
?
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow