-3

I really need help in casting from int to double. According to this problem, they want me to write a formula to calculate the average of the 3 grades from the sum using division and typecasting.

Here is my code so far, I don't know why it stays in int mode. Need help in number 5. Thanks

    public class Challenge1_6
    {

     public static void main(String[] args){
   
   // 1. Declare 3 int variables called grade1, grade2, grade3
   // and initialize them to 3 values

       int grade1 = 90;
       int grade2 = 100;
       int grade3 = 94;

   // 2. Declare an int variable called sum for the sum of the grades
   int sum;

  // 3. Declare a variable called average for the average of the grades
    int avg;
  // 4. Write a formula to calculate the sum of the 3 grades (add them up).
    sum = grade1 + grade2 + grade3;

  // 5. Write a formula to calculate the average of the 3 grades from the sum using division and type casting.
       avg =  sum / 3;
  
   
   

  // 6. Print out the average
      System.out.println((double)(avg));
Tommy Mai
  • 13
  • 2
  • It is impossible for you to be the first one on the internet to come across this problem. Please do your research before posting a question. – Harshal Parekh Aug 14 '20 at 23:12
  • 1
    I apologize. But it is your decision to answer the question or not. Don't go on here and be mean. Like other people, if you want to offer to help me then do so. If not, then don't. This is the internet, this post itself doesn't take up your personal space. If so, then I apologize. – Tommy Mai Aug 14 '20 at 23:28
  • Sorry, but I don't see it as being mean to ask you to follow the rules of this site. – NomadMaker Aug 14 '20 at 23:30
  • @TommyMai - my bad if I came off as mean, I didn't intend to. But like mentioned by NomadMaker - we expect everyone to follow the rules of the site. – Harshal Parekh Aug 14 '20 at 23:46
  • 5
    Does this answer your question? [Integer division: How do you produce a double?](https://stackoverflow.com/questions/3144610/integer-division-how-do-you-produce-a-double) – ken Aug 15 '20 at 14:36

1 Answers1

4

Replace

int avg;
avg =  sum / 3;

with

double avg =  sum / 3.0;

Alternatively,

double avg =  (double) sum / 3;
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
  • 1
    It still said I failed the assignment. It wants me to make a code that contains formula for average of 3 grades using sum and type casting to double – Tommy Mai Aug 14 '20 at 22:14
  • 1
    What is the "it" that says you failed? Some automatic grading system? The second solution given in this answer uses 'sum' and has 'casting to double' (and will give the correct result of 94.66...) – user13784117 Aug 15 '20 at 14:42