(一)用你的大数类实现加和减两个功能(乘除阶乘未实现)
import java.util.Scanner;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test {
public static int[] add(int[] a, int[] b) {
int digit = 0;
int[] c = new int[a.length];
for (int i = a.length - 1; i >= 0; i--) {
c[i] = a[i] + b[i] + digit;
if (c[i] < 10)
digit = 0;
else {
c[i] = c[i] - 10;
digit = 1;
}
}
return c;
}
public static int[] sub(int[] a, int[] b, int w) {
int digit = 0;
int[] c = new int[a.length];
for (int i = a.length - 1; i >= 0; i--) {
if (w <= 0) {
c[i] = b[i] - a[i] - digit;
if (c[i] >= 0)
digit = 0;
else {
c[i] = c[i] + 10;
digit = 1;
}
} else {
c[i] = a[i] - b[i] - digit;
if (c[i] >= 0)
digit = 0;
else {
c[i] = c[i] + 10;
digit = 1;
}
}
}
return c;
}
public static void main(String[] args) {
int a[] = new int[50];
int b[] = new int[50];
int m = 0;
int n = 0;
int s = 0;
int t = 0;
int w = 0;
Scanner reader=new Scanner(System.in);
System.out.print("请输入大数X:");
String X = reader.nextLine();
System.out.print("请输入大数Y:");
String Y = reader.nextLine();
m = a.length - X.length();
n = b.length - Y.length();
// 判断两个大数的大小
if (X.length() > Y.length())
w = 1;
else if (X.length() < Y.length())
w = -1;
else
w = X.compareTo(Y);
// 转化为数组
for (int i = 0; i < X.length(); i++) {
a[m++] = X.charAt(i) - 48;
}
for (int j = 0; j < Y.length(); j++) {
b[n++] = Y.charAt(j) - 48;
}
// 加法运算
int[] c = Test.add(a, b);
// 截取前面多余的0
for (int k = 0; k < c.length; k++) {
if (c[k] > 0) {
s = k;
break;
}
}
// 输出大数相加的结果
System.out.print("大数相加的结果为:");
for (int i = s; i < c.length; i++) {
System.out.print(c[i]);
}
// 减法运算
int[] d = Test.sub(a, b, w);
for (int k = 0; k < d.length; k++) {
if (d[k] > 0) {
t = k;
break;
}
}
System.out.print("\n");
System.out.print("大数相减的结果为:");
if (w < 0)
System.out.print("-");
for (int i = t; i < d.length; i++) {
System.out.print(d[i]);
}
}
}
(二)随机生成10个数,填充一个数组,然后用消息框显示数组内容,接着计算数组元素的和,将结果也显示在消息框中。
设计思路: 定义一个长度为10的数组,定义一个空字符串,让计算机随机产生十个数填充到数组中,将数组赋值给空字符串,取出数组中每个元素并求和,将和与数组在对话框中输出。
程序流程图:
源程序代码:
//数组求和 Jin Peigang 2015/10/28
import javax.swing.*;
public class Sum {
public static void main(String[]args){
int a[]=new int[10]; //创建一个数组a[10]并定义它的长度是10
int sum=0;
String output=" "; //定义一个字符串
for(int i=0;i<a.length;i++) //用计算机产生的十个数填充数组a[10]
{ a[i]=(int)(Math.random()*100+1);
output+=a[i]+" ";} //将数组赋值给字符串
output="a[10]={"+output+"}";
for(int i=0;i<a.length;i++) //取出数组元素求和
{sum+=a[i];}
output=output+"\n"+"sum:"+" "+sum;
JOptionPane.showMessageDialog(null,output,"数组求和", //对话框输出结果
JOptionPane.INFORMATION_MESSAGE);
}
}
结果截图:
问题:
Math.random()不规定范围能否随机产生十个数