题解 | #求平均数#

求平均数

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......


        //输出格式为:System.out.println(String.format("%.2f",avg));
        Scanner sc = new Scanner(System.in);
        float avg = 0;//平均数
        float sum = 0;//累加数
        float s = 0;//次数
        float n = 0;//暂存
        while (true) {
            s = sc.nextFloat();
            if (s < 0) {
                break;
            }
            sum += s;
            n++;
            avg = sum / n;
        }
        sc.close();
        System.out.println(String.format("%.2f", avg));


    }
}

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务