高精度運算——實數乘法

 

/*
*	@topic:實數乘法
*/
import java.util.Arrays;
import java.util.Scanner;
import java.util.regex.Pattern;

public class BigNumMult {
	static long[] a;/*被乘數*/
	static long[] b;/*乘數*/
	static long[] c;/*積*/

	public static void main(String args[]) throws Exception {
		//System.out.println("Hello Landor!");
		Scanner sc = new Scanner(System.in);
		String x = sc.next();
		String y = sc.next();
		System.out.println(mult(x, y));
	}

	public static String mult(String s1, String s2) throws Exception {
		int i, j;
		long m = 0;
		Pattern p = Pattern.compile("\\d*\\.?\\d*");
		if ((!p.matcher(s1).matches()) || (!p.matcher(s2).matches()))
			throw new Exception();
		a = new long[101];
		b = new long[101];
		c = new long[201];
		Arrays.fill(a, 0);
		Arrays.fill(b, 0);
		Arrays.fill(c, 0);
		int p1 = s1.indexOf(".");
		int p2 = s2.indexOf(".");
		if (p1 > -1)
			s1 = new StringBuffer(s1).deleteCharAt(p1).toString();/*去掉小數點*/
		if (p2 > -1)
			s2 = new StringBuffer(s2).deleteCharAt(p2).toString();
		int n1 = s1.length();
		int n2 = s2.length();
		for (i = 0; i < n1; i++)
			a[i + 1] = s1.charAt(n1 - i - 1) - '0';/*字符變數並按反序存放*/
		for (i = 0; i < n2; i++)
			b[i + 1] = s2.charAt(n2 - i - 1) - '0';
		for (i = 1; i <= n1; i++)
			for (j = 1; j <= n2; j++)
				c[i + j - 1] = c[i + j - 1] + a[i] * b[j];/*按位做乘法*/
		for (i = 1; i <= n1 + n2; i++) {
			c[i] += m;
			m = c[i] / 10;
			c[i] %= 10;
		}/*調整進位*/
		StringBuffer s = new StringBuffer();
		if (c[n1 + n2] != 0)
			s.append(c[n1 + n2]);//最高位如果是0則濾掉
		for (i = n1 + n2 - 1; i > n1 - p1 + n2 - p2; i--)
			s.append(c[i]);
		if (n1 - p1 + n2 - p2 != 0) {//若有小數部分則輸出
			s.append(".");
			for (i = n1 - p1 + n2 - p2; i > 0; i--)
				s.append(c[i]);
		}
		return s.toString();
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章