2017年6月23日 星期五

第八章 傳入陣列並計算其平均值

題目: 撰寫部論是傳入Int陣列或Float陣列,皆可以傳回陣列內所有元素平均值的方法

import java.util.Scanner;
class testAVG{
public static float intAVG(int []a,float []b){
float sum=0;

for(int i=0;i<a.length;i++){
sum+=a[i];
}
System.out.print(sum/a.length);
return sum/(a.length-1);

}
public static float floatAVG(int []a,float []b){
float sum=0;

for(int i=0;i<b.length;i++){
sum+=b[i];
}
System.out.print(sum/b.length);
return sum/(b.length-1);

}

}
public class HomeWork0808 {

public static void main(String[] args) {

System.out.println("請選擇\n1.整數\n2.浮點數");
Scanner sc=new Scanner(System.in);
int i=sc.nextInt();

if(i==1)
{
System.out.print("請輸入陣列長度");
int j=sc.nextInt();

int a[]=new int[j];
for(int k=0;k<j;k++){
a[k]=sc.nextInt();
}

float b[]=null;
testAVG.intAVG(a,b);
}
else if(i==2)
{
System.out.print("請輸入陣列長度");
int k=sc.nextInt();
float b[]=new float[k];
for(int m=0;m<k;m++){
b[m]=sc.nextFloat();
}
int a[]=null;
testAVG.floatAVG(a,b);
}
else
System.out.print("輸入錯誤");

sc.close();

}

}

沒有留言:

張貼留言