【发布时间】: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);
}
}
这是我的输出(它想要一个小数,但我不知道如何得到它):
【问题讨论】:
-
double average = sum / 3.0;: ideone.com/NViUIh -
sum / 3是整数运算。使其双重操作,方法是sum / 3.0