编写一个Java程序,使用+和/算术运算符找到三个数字的平均值。首先,它接受三个双数类型的数字,然后使用算术加号将它们相加,并使用/运算符找到平均值。
package RemainingSimplePrograms;
import java.util.Scanner;
public class AvgOfThree1 {
private static Scanner sc;
public static void main(String\[\] args) {
sc = new Scanner(System.in);
System.out.print("Please Enter the first Number = ");
double num1 = sc.nextDouble();
System.out.print("Please Enter the Second Number = ");
double num2 = sc.nextDouble();
System.out.print("Please Enter the Third Number = ");
double num3 = sc.nextDouble();
double average = (num1 + num2 + num3)/ 3;
System.out.println("\\nThe Average of Three Numbers = " + average);
}
在这个Java例子中,我们创建了一个calAvg函数,找到并返回三个数字的平均值。
package RemainingSimplePrograms;
import java.util.Scanner;
public class AvgOfThree2 {
private static Scanner sc;
public static void main(String\[\] args) {
sc = new Scanner(System.in);
System.out.print("Please Enter the first = ");
double num1 = sc.nextDouble();
System.out.print("Please Enter the Second = ");
double num2 = sc.nextDouble();
System.out.print("Please Enter the Third = ");
double num3 = sc.nextDouble();
double average = calAvg(num1, num2, num3);
System.out.println("\\nThe Average = " + average);
}
public static double calAvg(double a, double b, double c) {
return (a + b + c)/3;
}
Please Enter the first = 99
Please Enter the Second = 124.7
Please Enter the Third = 33.89
The Average = 85.86333333333333