代码:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
static string BigMulti(string &a, string &b)
{
string ret;
vector<int> v(a.length() + b.length() - 1, 0);
for (int i = 0; i < a.length(); i++) {
for (int j = 0; j < b.length(); j++) {
v[i + j] += (a[i] - '0') * (b[j] - '0');
}
}
int upper = 0;
int tmp;
char c;
for (int i = v.size() - 1; i >= 0; i--) {
tmp = upper + v[i];
c = (tmp % 10 + '0');
ret = c + ret;
upper = tmp / 10;
}
if (upper > 0) {
ret = to_string(upper) + ret;
}
return ret;
}
int main()
{
string str;
cin >> str;
string a, b;
// 用于统计小数点位数
int cntPoint = 0;
// 第一个乘数小数点距离末尾位数
int cntFirstVarPoint;
// 第二个乘数小数点距离末尾位数
int cntSecondVarPoint;
// 分割乘数为a和b
size_t idx = str.find_first_of('*');
a = str.substr(0, (idx - 1) - 0 + 1);
b = str.substr(idx + 1, (str.size() - 1) - (idx + 1) + 1);
int aLength = a.size();
int bLength = b.size();
//1.找出2个乘数的小数点位数 2.把a和b转换成两个整数string
size_t idxPoint1 = a.find_first_of('.');
size_t idxPoint2 = b.find_first_of('.');
if (idxPoint1 == string::npos) {
cntFirstVarPoint = 0;
} else {
cntFirstVarPoint = aLength - 1 - idxPoint1;
a.erase(idxPoint1, 1);
}
if (idxPoint2 == string::npos) {
cntSecondVarPoint = 0;
} else {
cntSecondVarPoint = bLength - 1 - idxPoint2;
b.erase(idxPoint2, 1);
}
cntPoint = cntFirstVarPoint + cntSecondVarPoint;
int j = cntPoint;
string result = BigMulti(a, b);
//计算小数点后0的个数
int i = result.size() - 1;
int cntZero = 0;
while (j--) {
if (result[i] == '0') {
cntZero++;
i--;
} else {
break;
}
}
if (cntZero == cntPoint) {
result.erase(result.size() - cntZero, cntZero);
} else {
result.insert(result.size() - cntPoint, 1, '.');
result.erase(result.size() - cntZero, cntZero);
}
cout << result << endl;
return 0;
}