题解 | #求平均数#
求平均数
https://www.nowcoder.com/practice/41e59cee1221424bb9291435aae79ae9
这一道题倒是挺耐人寻味的,题目给定的输入方式是两个数字之间有空格,但是实际输入的时候还是会有一行一个数字,分隔符是回车键,这个时候就不能够使用一次性读取的方法了,要检测键盘读入的状态。
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); //write your code here...... // String str1 = scan.nextLine() ; // String[] arr = str1.split(" ") ; // float sum = 0 ; // for(int i = 0 ; i < arr.length - 1 ; i ++){ // sum += Integer.parseInt(arr[i]); // } // float avg = sum/(arr.length - 1 ) ; // System.out.println(String.format("%.2f",(float)avg)); float sum = 0 ; int n = 0 ; while(scan.hasNext()){ float temp = (float)scan.nextInt() ; if(temp < 0){ break; } n ++ ; sum += temp ; } System.out.println(String.format("%.2f",sum/n)); //输出格式为:System.out.println(String.format("%.2f",avg)); } }