題目是編寫程序,讀入未指定個數的整數,判斷讀入的正數和負數分別有多少個,然後計算這些輸入值的總和及其平均值(不對0計數)。當輸入為0時,表明程序結束。將平均值以浮點數顯示。
import java.util.Scanner;
public class TextXXXXX {
public static void main (String[] args){
Scanner input = new Scanner(System.in);
int count1 = 0 , count2 = 0 , sum = 0 , num;
double avg;
System.out.print("請輸入一個整數,輸入0時結束:");
num = input.nextInt();
while(num != 0){
System.out.print("請輸入一個整數,輸入0時結束:");
num = input.nextInt();
while(num > 0)
count1+=1;
while(num < 0)
count2+=1;
sum+=num;
}
avg = sum /(count1 + count2);
System.out.println("整數個數為:" + count1 + " 負數個數為:" + count2);
System.out.println("和為:" + sum);
System.out.println("平均值為:"+ avg);
}
}
public static void main(String[] args) {
int count1 = 0, count2 = 0, sum = 0, num;
double avg;
for (int i = 1; i >0; i++) {
Scanner input = new Scanner(System.in);
System.out.print("請輸入一個整數,輸入0時結束:");
num = input.nextInt();
if (num > 0)
count1 += 1;
if (num < 0)
count2 += 1;
if(num==0){
break;
}
sum += num;
}
avg = sum*1.0 / (count1 + count2);
System.out.println("整數個數為:" + count1 + " 負數個數為:" + count2);
System.out.println("和為:" + sum);
System.out.println("平均值為:" + avg);
}