題目是
設計程式,利用鍵盤輸入數字,一直到輸入的數字為0才結束,然後顯示輸入的數字共有幾項,以及這些數字的總和、平均值、最大值和最小值。
import java.util.*;
public class sh
{
public static void main(String[] args)
{
ArrayList
Scanner scan = new Scanner(System.in);
int sum = 0, max = Integer.MIN_VALUE, min = Integer.MAX_VALUE, count = 0;
while (true)
{
System.out.print("請輸入一個整數 (輸入0即跳出 ): ");
int x = scan.nextInt();
if (x == 0) break;
if (!al.contains(x)) al.add(x);
sum += x;
if (x > max) max = x;
if (x < min) min = x;
count++;
}
System.out.println();
System.out.println("你輸入的數共(s):");
System.out.println(Arrays.toString(al.toArray()));
System.out.println("Sum of the number(s) you entered is " + sum);
System.out.println("Average is " + sum/count);
System.out.println("Max is " + max);
System.out.println("Min is " + min);
}
}
上面是我的回答,雖然顯示有幾項那個我做錯了
但整個程式執行沒問題,但老師跟我說不能用ArrayList
我整個無言,我是程式設計白痴,我坦承我大部分是是參考書的
但至少比抄的同學好吧!! 老師意思說叫我改掉ArrayList
用比較初學者的作法,用int a; 等
先宣告多個數值,再去印出結果
2007-12-07 12:24:25 · 3 個解答 · 發問者 ? 1 in 電腦與網際網路 ➔ 程式設計
//Power by Eclipse
//Download Site: http://www.eclipse.org/
import java.io.*;
import java.util.*;
public class TEST
//檔名:TEST.java
{
public static void main(String[] args)
{
PrintStream o=new PrintStream(System.out);
Scanner in=new Scanner(System.in);
double n[]=new double[32767];
int i=0;
do
{
o.printf("Input a number: ");
n[i]=in.nextDouble();
i++;
}
while(n[i-1]!=-1);
o.printf("The numbers of Input= %d\nSum= %f\n",i-1,sum(i-1,n));
o.printf("Average= %f\n",sum(i-1,n)/(i-1));
sort(i-1,n);
o.printf("Max= %f\nMin= %f\n",n[0],n[i-2]);
}
public static double sum(int Length, double Number[])
{
double sum=0;
for(int i=0;i
sum+=Number[i];
}
return sum;
}
public static void sort(int Length, double Number[])
{
double tmp;
for(int i=0;i
for(int j=i;j
if(Number[i]
tmp=Number[i];
Number[i]=Number[j];
Number[j]=tmp;
}
}
}
}
}
2007-12-08 14:52:03 補充:
……上面是輸入-1即跳出
2007-12-07 18:11:24 · answer #1 · answered by Big_John-tw 7 · 0⤊ 0⤋
我想只有在學校
程式才有所謂的標準答案吧
2007-12-08 09:19:36 · answer #2 · answered by elastic 7 · 0⤊ 0⤋
請參考我的做法
import java.util.*;
public class Y05873 {
public static void main(String[] args) {
int sum = 0, max = Integer.MIN_VALUE, min = Integer.MAX_VALUE, count = 0;
int[] ary = new int[1000];
Scanner scan = new Scanner(System.in);
while (true) {
if (count > ary.length - 100) ary = Arrays.copyOf(ary, ary.length*2);
System.out.print("請輸入一個整數 (輸入0即跳出 ): ");
int x = scan.nextInt();
if (x == 0) break;
sum += x;
if (x > max) max = x;
if (x < min) min = x;
ary[count++] = x;
}
System.out.println("你輸入的數字為");
StringBuffer sb = new StringBuffer("[");
for (int i = 0; i < ary.length; i++) {
if (ary[i] == 0) break;
sb.append(ary[i] + ", ");
}
System.out.println(sb.substring(0, sb.length()-2) + "]");
System.out.println("總和為 " + sum);
System.out.println("平均為 " + (sum + 0D)/count);
System.out.println("最大值為 " + max);
System.out.println("最小值為 " + min);
}
}
2007-12-07 21:19:21 · answer #3 · answered by ? 7 · 0⤊ 0⤋