大浮点数相乘
Posted 守夜人
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了大浮点数相乘相关的知识,希望对你有一定的参考价值。
import java.util.Scanner;
public class BigMultiply {
/**
* 大数相乘基本思想,输入字符串,转成char数组,转成int数组。采用分治思想,每一位的相乘;<br>
* 公式:AB*CD = AC (BC+AD) BD , 然后从后到前满十进位(BD,(BC+AD),AC)。
* @param num1
* @param num2
*/
public static String multiply(char[] chars1, char[] chars2){
//声明存放结果和两个乘积的容器
int result[] = new int[chars1.length + chars2.length];
int n1[] = new int[chars1.length];
int n2[] = new int[chars2.length];
//把char转换成int数组,为什么要减去一个‘0‘呢?因为要减去0的ascii码得到的就是实际的数字
for(int i = 0; i < chars1.length;i++)
n1[i] = chars1[i]-‘0‘;
for(int i = 0; i < chars2.length;i++)
n2[i] = chars2[i]-‘0‘;
//逐个相乘,因为你会发现。AB*CD = AC(BC+AD)BD , 然后进位。
for(int i =0 ; i < chars1.length; i++){
for(int j =0; j < chars2.length; j++){
result[i+j]+=n1[i]*n2[j];
}
}
//满10进位,从后往前满十进位
for(int i =result.length-1; i > 0 ;i--){
result[i-1] += result[i] / 10;
result[i] = result[i] % 10;
}
//转成string并返回
String resultStr = "";
for(int i = 0; i < result.length-1; i++){
resultStr+=""+result[i];
}
return resultStr;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String num1 = scanner.next();
String num2 = scanner.next();
int count1 = (num1.indexOf(‘.‘));
int count2 = (num2.indexOf(‘.‘));
int N1 =0;
int N2 =0;
//把字符串转换成char数组
char chars1[] = num1.toCharArray();
char chars2[] = num2.toCharArray();
int count =0;
if(count1>0) {
N1 = num1.length()-1;
count = num1.length()-count1-1;
}
else N1=num1.length();
if(count2>0) {
N2 = num2.length()-1;
count = count + num2.length()-count2-1;
}
else N2=num2.length();
char ch1[] = new char[N1] ;
char ch2[] = new char[N2] ;
for(int i=0,j=0;i<num1.length();i++) {
if(i!=count1) {
ch1[j]=chars1[i];
j++;
}
}
for(int i=0,j=0;i<num2.length();i++) {
if(i!=count2) {
ch2[j]=chars2[i];
j++;
}
}
String result = multiply(ch1, ch2);
count=result.length()-count;
result = result.substring(0, count)+"."+result.substring(count, result.length());
System.out.println(result);
scanner.close();
}
}
以上是关于大浮点数相乘的主要内容,如果未能解决你的问题,请参考以下文章