3864 - 4.1 统计正数和负数的个数然后计算这些数的平均值

通过次数

0

提交次数

0

时间限制 : 1 秒 内存限制 : 128 MB

编写程序,读入未指定个数的整数,判定读入的正数有多少个,读入的负数有多少个,然后计算这些输入值的总和及其平均值(不对0计算)当输入为0时,表明程序结束。将平均值以浮点数显示(小数点后保留2位四舍五入)。

题目输入

输入若干个整数

题目输出

输出:

The number of positives is 正数个数

The number of negatives is 负数个数

The total is 数的总和

The average is 数的平均数

输入/输出样例

输入格式

1 2 -1 3 0

输出格式

The number of positives is 3
The number of negatives is 1
The total is 5
The average is 1.25

Java解答

import java.util.Scanner;


public class Main {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner input=new Scanner(System.in);
		int a=input.nextInt();
		int p=0,n=0,t=0;
		while (a!=0) {
			t+=a;
			if (a>0) p++;
			else n++;
			a=input.nextInt();
		}
		System.out.println("The number of positives is "+p);
		System.out.println("The number of negatives is "+n);
		System.out.println("The total is "+t);
		System.out.printf("The average is %.2f",(t*1.0/(p+n)));
	}

}