【问题标题】:Is there a way that I can cast the variables in my Java program so that I get a double output?有没有办法可以在我的 Java 程序中转换变量,以便获得双重输出?
【发布时间】:2023-04-07 05:50:01
【问题描述】:

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

以下是程序说明:

在下面的代码中,输入三个组成的 int 等级,然后求和 平均他们。使用强制转换将结果报告为双精度数。为了 例如,如果成绩是 90、100 和 94,则三者之和 数字是 90 + 100 + 94 = 284,平均值是总和 284 除以 乘以 3 的两倍是 94.666667。你应该使用你的 变量而不是公式中的数字。跟着 伪代码如下。

输入三个组成的 int 等级,然后对它们求和并取平均值。采用 类型转换以将结果报告为双精度。

这是我的代码:

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 = sum / 3.0;: ideone.com/NViUIh
  • sum / 3 是整数运算。使其双重操作,方法是sum / 3.0

标签: java casting average


【解决方案1】:

好吧,平均变量必须是两倍 然后您将除法结果转换为适合平均变量

    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);

【讨论】:

    【解决方案2】:

    只需将变量“平均”更改为双倍。

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

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

    【讨论】:

      【解决方案3】:

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

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

      Demo!

      【讨论】:

        【解决方案4】:

        只需将平均值转换为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);
           }
        }
        

        【讨论】:

          猜你喜欢
          • 2013-05-12
          • 1970-01-01
          • 2015-05-04
          • 2021-01-04
          • 1970-01-01
          • 2018-10-23
          • 2013-05-10
          • 2021-02-24
          • 2020-01-04
          相关资源
          最近更新 更多