英文:
Average of numbers program outputting incorrect result
问题
尝试编写一个简单的程序来计算3个整数值的平均值,但它似乎总是计算出错误的平均值。
import java.util.Scanner;
public class IntegerAverage {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int num1;
int num2;
int num3;
// 询问用户
System.out.println("输入第一个数字");
num1 = in.nextInt();
System.out.println("输入第二个数字");
num2 = in.nextInt();
System.out.println("输入第三个数字");
num3 = in.nextInt();
// 输出答案
System.out.println("平均值是:" + ((num1 + num2 + num3) / 3));
}
}
感谢您的帮助
英文:
Am trying to write simple program to find average of 3 int values, but it always seems to get the average wrong
import java.util.Scanner;
public class IntegerAverage {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int num1;
int num2;
int num3;
// Ask user
System.out.println("Input 1st number");
num1 = in.nextInt();
System.out.println("Input 2nd number");
num2 = in.nextInt();
System.out.println("Input 3rd number");
num3 = in.nextInt();
// Print answer
System.out.println("The average is:"+ ((num1 + num1 + num3)/3));
}
}
Help is greatly appreciate
答案1
得分: 1
除了已经在上面提到的两次num1
和缺少的num2
,你将始终只会得到整数结果,例如对于num1 = 1
,num2 = 2
和num3 = 2
,你的代码将会将1
作为结果绘制,而不是1.667
。你可以通过写入以下内容来强制在输出中获得双精度结果:
System.out.println("The average is:" + ((num1 + num2 + num3) / 3.0));
英文:
Besides having num1
twice and missing num2
, as already mentioned above, you will always get integer-results only, e.g. for num1 = 1
, num2 = 2
and num3 = 2
your code will plot 1
as result instead of 1.667
. You might enforce double-results in your output by writing
System.out.println("The average is:"+ ((num1 + num2 + num3) / 3.0));
答案2
得分: 0
它应该是这样的:
import java.util.Scanner;
public class IntegerAverage {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int num1;
int num2;
int num3;
// 询问用户
System.out.println("输入第一个数字");
num1 = in.nextInt();
System.out.println("输入第二个数字");
num2 = in.nextInt();
System.out.println("输入第三个数字");
num3 = in.nextInt();
// 输出答案
System.out.println("平均值为:" + ((num1 + num2 + num3) / 3));
}
}
你不小心把num1重复了一次,并且忘记了num2。
英文:
It's supposed to be:
import java.util.Scanner;
public class IntegerAverage {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int num1;
int num2;
int num3;
// Ask user
System.out.println("Input 1st number");
num1 = in.nextInt();
System.out.println("Input 2nd number");
num2 = in.nextInt();
System.out.println("Input 3rd number");
num3 = in.nextInt();
// Print answer
System.out.println("The average is:"+ ((num1 + num2 + num3)/3));
}
}
You accidentally added num1 twice, and forgot num2.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论