2

I need java to keep the results their true values, here is my code:

`

Scanner scan = new Scanner(System.in);
int test1;
int test2;
int quiz1;
int quiz2;
int quiz3;
double homework;
System.out.println("Please enter your test grades.");
test1 = scan.nextInt();
test2 = scan.nextInt();
System.out.println("Please enter you quiz grades.");
quiz1 = scan.nextInt();
quiz2 = scan.nextInt();
quiz3 = scan.nextInt();
System.out.println("Please enter your homework average.");
homework = scan.nextDouble();
double quizaverage = (quiz1 + quiz2 + quiz3)/3;
double testaverage = (test1 + test2)/2;
System.out.println("Test Average " + (testaverage) + "");
System.out.println("quiz Average " + (quizaverage) + "");
double finalgrade = (testaverage) * 0.5 + (quizaverage)* 0.3 + (homework) * 0.2;
System.out.println("Final Grade " + (finalgrade) + "");`

The values I am inputting: *test 1=89, test 2=86, quiz 1=84, quiz 2=84, quiz 3=83, homework=90.12*

Everything works but the problem is I need the test average variable and quiz average variable to not round down, because I am getting 87.0 for my test average and 83.0 for my quiz average when I run the program, those values then affect the final grade variable because I need to get 86.874 for the final grade, not 86.424. so I their true values of 87.5 for the test average and 83.66666666666667 for the quiz average to get the true final grade. Basically I need to know how to prevent java from rounding down (I think). I hope I did not make it sound complicated, all help is appreciated.

nm6
  • 23
  • 5
  • 1
    possible duplicate of [wrong division in java](http://stackoverflow.com/questions/3553047/wrong-division-in-java) – MrTux Sep 17 '14 at 22:17

1 Answers1

3

You are performing integer division, which in Java results in another int. You need to force floating-point division with your math; assigning to a double doesn't force it. Use a floating-point literal, with .0 on the end.

double quizaverage = (quiz1 + quiz2 + quiz3)/3.0;
double testaverage = (test1 + test2)/2.0;

(Casting either operand to a double would work also.)

rgettman
  • 176,041
  • 30
  • 275
  • 357
  • I also found that using casts and making it ``((double)quiz1 + (double)quiz2 + (double)quiz3)/3;`` also worked. – nm6 Sep 17 '14 at 22:40