有没有一种方法可以在我的 Java 程序中转换变量以获得双输出?

Is there a way that I can cast the variables in my Java program so that I get a double output?

我是 Java 的初学者,我被要求编写一个程序来计算三个年级的平均值。我想弄清楚如何通过类型转换获得双重输出,但我不知道在哪里转换。我已经自己写了一些代码,但评分者仍然说我没有得到正确的答案。

程序说明如下:

In the code below, type in three made up int grades and then sum and average them. Use casting to report the result as a double. For example, if the grades are 90, 100, and 94, the sum of the three numbers is 90 + 100 + 94 = 284, and the average is the sum 284 divided by 3 which casted to a double is 94.666667. You should use your variables instead of the numbers in your formulas. Follow the pseudocode below.

Type in three made up int grades and then sum and average them. Use type casting to report the result as a double.

这是我的代码:

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 = 78;
       int grade2 = 95;
       int grade3 = 84;

      // 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 average;
      // 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.
       average = sum / 3;
      // 6. Print out the average
       System.out.println(average);
   }
}

这是我的输出(需要小数但我不知道如何得到):

enter image description here

嗯,平均变量必须是双倍的 然后将除法结果放入平均变量

    double average;
    // 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.
    average = (double) sum / 3;
    System.out.println(average);

您可以简单地除以双字面值 3.03d,以便它执行浮点除法而不是除法。

double average;
sum = grade1 + grade2 + grade3;
average = sum / 3.0;

Demo!

只需将平均值转换为 double 即可避免因从 double 转换为 int

而导致的任何遗漏
public class Challenge1_6 {
   public static void main(String[] args) {
       int grade1 = 78;
       int grade2 = 95;
       int grade3 = 84;

       int sum;
       double average;
       sum = grade1 + grade2 + grade3;
       average = sum / 3;
       System.out.println(average);
   }
}

只需将变量“average”更改为 double。

double average=Double.valueOf(sum / 3);

逻辑是: 函数中至少有一个变量(a/b)应该是double类型 或者我们需要根据需要将int值转换为Double。