解题思路:
显然根据题意要求浮点数和2的幂n相乘的四舍五入的整数部分,先获取小数的个数,可以用高精度乘法和快速幂结合来求2的幂,存放在数组里,在往小数部分检查如果大于5就往前进位,这是高精度加法,只用一次循环,然后输出整数部分就行
注意事项:
高精度运算结束都要处理进位或者前导0的问题
参考代码:
#include <iostream> #include<vector> #include<algorithm> #include<string> #include<queue> #include<cstring> using namespace std; int n, m, k; int T, ncase = 0; const int N = 1e4 + 3; string b; vector<int> bb; vector<int> a; vector<int>sum; int d; void check() { bool ok = false; int index = 0; int co = 0; for (int i = d-1; i >= 0; i--) { if (sum[i]>=5) { ok = true; co = 1; index = i + 1; break; } else if (sum[i] <= 4) { continue; } } if (ok) { for (int i = index; i < sum.size(); i++) { int di = sum[i] + co; sum[i] = di % 10; co = di / 10; } } if (co) { sum.push_back(1); } for (int i = sum.size() - 1; i >= d; i--) { cout << sum[i]; } } void mul() { a.push_back(2); while (n) { if (n & 1) { vector<int>ve(sum.size() + a.size() + 1, 0); for (int i = 0; i < sum.size(); i++) { for (int j = 0; j < a.size(); j++) { ve[i + j] += sum[i] * a[j]; ve[i + j + 1] += ve[i + j] / 10; ve[i + j] %= 10; } } while (ve.size() && ve.back()==0)ve.pop_back(); sum = ve; } vector<int>ve(a.size() + a.size() + 1, 0); for (int i = 0; i < a.size(); i++) { for (int j = 0; j < a.size(); j++) { ve[i + j] += a[i] * a[j]; ve[i + j + 1] += ve[i + j] / 10; ve[i + j] %= 10; } } while (ve.size() && ve.back() == 0)ve.pop_back(); a = ve; n >>= 1; } check(); } int main() { ios_base::sync_with_stdio(0); cin >> n >> b; d = b.find('.'); b.erase(b.begin() + d); d = b.size() - d; for (int i = 0; i < b.size(); i++) { if (b[i] == '.')continue; else bb.push_back(b[i] - '0'); } sum = bb; reverse(sum.begin(), sum.end()); mul(); return 0; }
0.0分
3 人评分