运行时数组,用于计算浮点数据类型的总和和平均值

时间:2017-10-16 20:34:40

标签: java arrays floating-point java.util.scanner

在创建运行时创建数组大小的程序时遇到问题,显示数组大小,将数字的总和和平均值四舍五入到小数点后两位。

The number before the decimal point is: 36 The number after decimal point is: 5

的System.out.println(Arrays.toString(输入));

2 个答案:

答案 0 :(得分:0)

首先,数组的长度是int,而不是float。

其次,您必须实际使用您刚刚获得的用户输入,而不是length

第三,你应该使用float或double数组来执行你的操作,但为此你需要对输入进行类型转换。

 // taking Int array length input from user
Scanner input = new Scanner(System.in);
System.out.println("Please enter length of the array");
int arrayLength= input.nextInt();

// create a array to save user input
float[] input = new float[arrayLength];

我建议您查看您不了解的所有条款。

答案 1 :(得分:0)

public static void main(String[] args){
    System.out.println("Program creates array size at run-time");
    System.out.println("Program rounds sum and average of numbers to two decimal places");
    System.out.println("Note: numbers *must* be float data type");
    System.out.println(); //blank line

    // taking String array input from user
    Scanner input = new Scanner(System.in);
    System.out.println("Please enter length of String array");
    float length = input.nextFloat();

    // create a String array to save user input
    String[] arr = new String[(int)length];

// loop over array to save user input
    System.out.println("Please enter array elements");
    for (int i = 0; i < length; i++) {
        String userInput = Float.toString((input.nextFloat()));
        arr[i] = userInput;
    }

    float sum = 0;

    System.out.println("The String array input from user is : ");
    for(int i = 0; i < arr.length; i++){
        System.out.println(String.format("%.2f", Float.valueOf(arr[i])));
        sum += Float.valueOf(arr[i]);
    }
    System.out.println("The sum is: " + String.format("%.2f",sum));

    System.out.println("The average is: " + String.format("%.2f",(sum/length)));
}

这应该有用,虽然我还没有测试过。