我叫王超然,是一名电脑爱好者,现在在新加坡留学上高一.我立志成为一名电脑人才,愿意在这里与大家一同分享我玩转电脑的心得.O-level华文考了A-One哈哈!
天气: 晴朗
心情: 高兴
/*P3Q2
* Wang Chaoran
Description:2 (Counting positive and negative numbers and
computing the average of numbers)
Write a program that reads an unspecified number of integers,
determines how many positive and negative values have been read,
and computes the total and average of the input values, not counting zeros.
Your program ends with the input 0. Display the average as a floating-point number.
(For example, if you entered 1, 2, and 0, the average should be 1.5.)
*/
import java.util.Scanner;
public class P3Q2
{
public static void main(String[] args)
{
//Create scanner
Scanner scan = new Scanner(System.in);
double input = 1,countPositive=0,countNegative=0,sum=0;
//Read in unspecified number of integers
while (input!=0)
{
System.out.println("Please enter an integer(when you enter '0', \nthe program will count how many positive and negative values have been read, \nand computes the total and average of the input values, not counting zeros):");
input = scan.nextInt();
if(input>0)
{
sum+=input;
countPositive++;
}
else if(input<0)
{
sum+=input;
countNegative++;
}
}
//Calculate average
float average=(float)((sum)/(countPositive+countNegative));
//Print the result
System.out.println("The program has read "+(int)countPositive+" positive integers and "+(int)countNegative+" negative integers");
System.out.println("Total value of the input average(not counting zeros)is "+average+ ". Total value of the input is "+(int)sum);
}
}
导入论坛查看(34)回复(0)引用(0)好评(0) 差评(0)
加入收藏
编辑
审核
TAG:
computing