实验2
《Java程序设计》实验2
1、使用Java语言编程,从键盘输入N个整数存储到数组中,求数组所有元素的和、最大值、最小值和平均值(注:数据个数N需要从键盘输入,平均值采用数学含义的平均值)
方法1
import java.util.Scanner;
public class Main {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("请输入元素个数:");
int n = sc.nextInt();
int [] x = new int [n];
int max, min, avg, sum = 0;
max = min = n;
for (int i = 0; i < n; i ++) {
System.out.print("请输入数组各元素的值:");
x[i] = sc.nextInt();
//求和
sum = sum + x[i];
//求极值
if (max < x[i]) max = x[i];
if (min > x[i]) min = x[i];
}
sc.close();
System.out.println("\u005B");
System.out.println(" 和:" + sum);
System.out.println("最大值:" + max);
System.out.println("最小值:" + min);
System.out.println("平均值:" + sum / n);
System.out.println("\u005d");
}
}
方法2:
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int sum = 0, max = 0, min = 0;
double ave;
int count = 0;
int b = 0, c = 100000;
while (sc.hasNextInt()) {
int a = sc.nextInt();
sum += a;
if (b < a) {
max = a;
}
if (c > a) {
min = a;
}
b = a; c = a;
count ++;
}
ave = (double)sum / count;
System.out.printf("%d个数的和 = %d\n", count, sum);
System.out.printf("%d个数的最大值 = %d\n", count, max);
System.out.printf("%d个数的最小值 = %d\n", count, min);
System.out.printf("%d个数的平均值 = %.2f\n", count, ave);
}
}
2、使用Java语言编程,产生10000个1~9之间的随机数,统计每个数出现的概率。
ora...
public class Main {
public static void main(String[] args) {
int [] array = new int [10];
for (int i = 0; i < 10000; i ++) {
//array[i - 1]统计 i 出现的次数
array[(int)(Math.random() * 10)] ++;
}
for (int i = 0; i < array.length; i ++) {
System.out.println(i + 1 + "出现的次数" + array[i]);
}
}
}
low...
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n[] = new int[10000];// 定义一个100个长度的一维数组
for (int i = 0; i < 10000; i++) {// 这是100个数。。。
n[i] = (int) (1 + Math.random() * 8);
}
for (int i = 0; i < 10000; i++) {// 这里输出了10行10列的0.好多好多啊100个。
if (i % 50 == 0 && i != 0) {
System.out.println();
}
System.out.print(n[i]);
System.out.printf(" ");
}
}
}
3、使用Java语言编程,从键盘输入10个整数,并存放到一个数组中,然后将其前5个元素与后5个元素对换,即:第1个元素与第10个元素互换,第2个元素与第9个元素互换,......,第5个元素与第6个元素互换。分别输出数组原来各元素的值和互换后各元素的值
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int[] x= new int[15];
for (int i = 1; i <= 10; i ++)
{
x[i] = sc.nextInt();
}
for (int i = 1; i <= 5; i ++) {
int tmp = x[i];
x[i] = x[11 - i];
x[11 - i] = tmp;
}
for (int i = 1; i <= 10; i ++) {
System.out.printf("x[%d]=%d\n", i, x[i]);
}
}
}
本文来自博客园,作者:逆袭怪,转载请注明原文链接:https://www.cnblogs.com/fghjktgbijn/p/17645381.html