Reputation: 37
I'm having some problem with my code. It works fine when I compile it until I get to the point when the numbers divide. I'm not getting numbers with decimal, only zero. As you can see, I already changed the last variables to double but it didn't have any meaningful result.
What must I do to change this?
int[] arr = new int[2];
System.out.println("enter two numbers: ");
arr[0] = sc.nextInt();
arr[1] = sc.nextInt();
int summa = arr[0]+arr[1];
System.out.println("What's "+arr[0]+" + "+arr[1]+" ?");
int vad = sc.nextInt();
if (summa == vad)
System.out.println("Correct!");
else
System.out.println("Wrong - The right answer is "+summa);
int summa2 = arr[0]-arr[1];
System.out.println("What's "+arr[0]+" - "+arr[1]+" ?");
int vad2 = sc.nextInt();
if (summa2 == vad2)
System.out.println("Correct!");
else
System.out.println("Wrong - The right answer is: "+summa2);
int summa3 = arr[0]*arr[1];
System.out.println("What's "+arr[0]+" * "+arr[1]+" ?");
int vad3 = sc.nextInt();
if (summa3 == vad3)
System.out.println("Correct!");
else
System.out.println("Wrong - The right answer is "+summa3);
double summa4 = arr[0]/arr[1];
System.out.println("What's "+arr[0]+" / "+arr[1]+" ?");
double vad4 = sc.nextInt();
if (summa4 == vad4)
System.out.println("Correct!");
else
System.out.println("Wrong - The right answer is "+summa4);
}
}
Upvotes: 0
Views: 89
Reputation: 22104
Although summa4 variable is of type double, but it's calculation is done in integer division. Therefore, the result would not have any decimal place.
For example, 5/2 = 2 and not 2.5 if both 5 and 2 are integers or values stored in int type variable.
change:
double summa4 = arr[0]/arr[1];
to
double summa4 = 1.0*arr[0]/arr[1];
Upvotes: 2
Reputation: 240898
1 you are reading int it should be double .
2 You need to cast to double check code below
double summa4 = ((double)arr[0])/arr[1];
System.out.println("What's "+arr[0]+" / "+arr[1]+" ?");
double vad4 = sc.nextDouble();
if (summa4 == vad4)
System.out.println("Correct!");
else
System.out.println("Wrong - The right answer is "+summa4);
Upvotes: 4