1

What is wrong with this quote? It always outputs 0.0 instead of the total score result

import java.util.Scanner;

public class d {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        int num1;
        int num2;
        int num3;
        int percentnum1;
        int percentnum2;
        int percentnum3;
        double totalscore;

        System.out.print("Enter paper 1 score (out of 90): ");
        num1 = input.nextInt();

        System.out.print("Enter paper 2 score (out of 90): ");
        num2 = input.nextInt();

        System.out.print("Enter IA score (out of 20): ");
        num3 = input.nextInt();

        percentnum1 = (num1 / 90) * 100;
        percentnum2 = (num2 / 90) * 100;
        percentnum3 = (num3 / 20) * 80;

        totalscore = (percentnum1 * 0.4) + (percentnum2 * 0.4) + (percentnum3 * 0.2);

        System.out.println("The total score is " + totalscore);


    }
}
c0der
  • 18,467
  • 6
  • 33
  • 65

3 Answers3

0

seems like the code below is causing the problem:

percentnum1 = (num1 / 90) * 100;
percentnum2 = (num2 / 90) * 100;
percentnum3 = (num3 / 20) * 80;

if all of num1, num2 and num3 are values less than its denominators the result (totalscore) will be 0.0 because of integer division, even if some of the variables were 90/90 or 20/20 and others were less than it's denominators, you would again get the incorrect result and again due to integer division (though this time not necessarily 0.0).

The solution is to simply, use double types to keep the precision.

double num1;
double num2;
double num3
double percentnum1;
double percentnum2;
double percentnum3;
double totalscore;
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
0

Change int to double to avoid rounding down to 0.

c0der
  • 18,467
  • 6
  • 33
  • 65
0

If you like to use int types, you can multiply the number first. Hope it is helpful.

percentnum1 = num1 * 100 / 90;
percentnum2 = num2 * 90 / 100;
percentnum3 = num3 * 80 / 20;
Cheng Pan
  • 1
  • 1