gpt4 book ai didi

java - 我的平均公式没有给出确切的答案

转载 作者:行者123 更新时间:2023-12-02 10:08:27 25 4
gpt4 key购买 nike

我创建了一个 Java 程序,它接受三个整数并打印总和、乘积、最小和最大以及这三个整数的平均值。

import java.util.Scanner;

public class ThreeNums
{
public static void main (String[] args)
{
new ThreeNums();
}

public ThreeNums ()
{
int num1, num2, num3, sum, smallest, largest, exitPrompt = 0;
float average;

Scanner scan = new Scanner (System.in);

while (exitPrompt == 0)
{
System.out.printf ("\n\nPlease enter three integers.\n");
System.out.printf ("\t1st integer: ");
num1 = scan.nextInt();
System.out.printf ("\t2nd integer: ");
num2 = scan.nextInt();
System.out.printf ("\t3rd integer: ");
num3 = scan.nextInt();
System.out.printf ("\n");

sum = num1+num2+num3;
System.out.println ("Sum: " + sum);
System.out.printf ("Product: %d\n", num1*num2*num3);

if (num1<num2)
smallest = num1;
else
smallest = num2;

if (smallest<num3)
smallest = smallest;
else
smallest = num3;

if (num1>num2)
largest = num1;
else
largest = num2;

if (largest>num3)
largest = largest;
else
largest = num3;

System.out.printf ("Smallest integer: %d\n", smallest);
System.out.printf ("Largest integer: %d\n", largest);

average = sum/3;
System.out.printf ("Average: %.3f\n", average);

System.out.printf ("\nExit? 0 if NO, any other digit if YES\n");
exitPrompt = scan.nextInt();
}

System.out.printf ("\n\n");
}
}

一切都很好,除了(我认为)第 56-57 行:

average = sum/3;
System.out.printf ("Average: %.3f\n", average);

它应该打印用户输入的三个整数的平均值。例如,如果用户输入 5、7、7,则应该显示平均值为 6.333:

Please enter three integers.
1st integer: 5
2nd integer: 7
3rd integer: 7

Sum: 19
Product: 245
Smallest integer: 5
Largest integer: 7
Average: 6.333

Exit? 0 if NO, any other digit if YES

但是,对于平均值,它仅显示 6.000。

.
.
.
Average: 6.000
.
.

如果我输入 78、45 和 23,它只显示 48.000,而不是 48.667,依此类推。我的代码可能有什么问题?请帮忙...谢谢!

最佳答案

这里:average = sum/3; sum3 都是 int,所以结果是一个 int,然后将其转换为 float。您可以通过以下方法克服这个问题:

average = sum / 3.0;

关于java - 我的平均公式没有给出确切的答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55169439/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com