首页 > 试题广场 >

(统计正教和负數的个教然后计算这些教的平均值)编写程序,读

[问答题]
 (统计正教和负數的个教然后计算这些教的平均值)编写程序,读人未指定个数的整数,判断读人 的正数有多少个,读入的负数有多少个,然后计算这些输人值的总和及其平均值(不对 0 计数)。 当输人为 0时,表明程序结束。将平均值以浮点数显示。下面是一个运行示例:

public class Test {
	public static void main(String[] args){
	
		//程序说明:用户读入整数,程序显示对应数据
		//提示用户输入整数
		System.out.print("Enter an interger,the input ends if it is 0:");
		Scanner input = new Scanner(System.in);
		int n = input.nextInt();
		
		int positives = 0,negatives = 0,t = 0;
		double total = 0,average = 0;
		
		//计算并显示相应的数据
		while(n != 0){
			if(n > 0)
				positives++;
			else
				negatives++;
			total += n;
			t++;
			n = input.nextInt();
		}
		average = total / t;
		if(t == 0)
		{
			System.out.println("please input.");
			return;
		}
		System.out.println("The number of positives is:" + positives);
		System.out.println("The number of negatives is:" + negatives);
		System.out.println("The total is:" + total);
		System.out.println("The average is:" + average);
    }
}

发表于 2020-02-25 09:47:47 回复(0)