0

I am writing a program to get the percentage total of each letter grade. Eventually the output should be,

Total number of grades: ...

Number of A's: ... : %

Number of B's: ... : %

and etc until F's. When the code is run the output for the percentages return as zero. I'm not quite sure why. I would apprieciate the help. Thank you everyone!

Heres a code sample:

    System . out . println ("Please enter a list of exam scores: " ) ;
  System . out . println ("*Note* Enter a negative number after all scores have been entered." ) ;


  do {
 num = input . nextInt () ;


  if ( num >= 90 && num <= 100 ) {
 totalA ++;
  } else if ( num >= 80 && num <= 89 ) {
 totalB ++;
  } else if ( num >= 70 && num <= 79 ) {
 totalC ++;
  } else if ( num >= 60 && num <= 69 ) {
 totalD ++;
  } else if ( num <= 59 && num >= 0 ) {
 totalF ++;
  }
  if ( num >= 0 ) {
 count ++;
  }

  }while ( num >= 0 ) ;

 totalAP = Math . rint ((totalA / count ) * 100 ) ;


  System . out .println ( totalAP ) ;

I am just calulationg the A percentages for now.

  • If totalA and count are int, you’re doing integer math. `2 / 10` is zero, since both operands are ints and the result is int, but `2.0 / 10.0` is 0.2. Try changing your code to `Math.rint(((double) totalA / count) * 100)`. If one operand is a double, all operands are promoted to double. – VGR Mar 17 '19 at 04:45

1 Answers1

0

If totalA and count are both int objects, and count is greater than totalA, the result of totalA/count will be a decimal answer, eg. 0.65 but in an int, the decimals are truncated, returning 0 and 0*100 = 0. Make totalA a double or cast it as a double, and you should get the correct answer.

spinyBabbler
  • 392
  • 5
  • 19