每个句子由多个单词组成,句子中的每个单词的长度都可能不一样,给出整个句子的单词平均长度
package com;
import java.math.BigDecimal;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println(avg(s.nextLine()));
}
public static String avg(String words){
String[] arr = words.split(" ");
int sum = 0;
for(int i=0;i<arr.length;i++){
sum += arr[i].length();
}
return (new BigDecimal(String.valueOf(sum))).divide(new BigDecimal(String.valueOf(arr.length)), 2, BigDecimal.ROUND_HALF_UP).toPlainString();
}
}
如:
输入:Who Love Solo
输出:3.67