核心就是要将乘以2的n次方转换为累加的操作
证明
$$
x 2^{n} = x 2 2...2 = (x + x) 2...2
$$
证明
$$
x 2^{n} = x 2 2...2 = (x + x) 2...2
$$
#include <iostream>
#include <string>
using namespace std;
void add(string& a, string& b){
// 保证两个字符串的长度是一样的
int t = 0;
for(int i = 0; i < a.size(); ++ i){
t += a[i] - '0' + b[i] - '0';
a[i] = t % 10 + '0';
t /= 10;
}
if(t) a.push_back('1');
}
int main(){
ios::sync_with_stdio(false);
int n;
string d;
cin >> n >> d;
string s;
int pos;
for(int i = d.size() - 1, j = 0; i >= 0; -- i){
if(d[i] != '.'){
s.push_back(d[i]); // 逆序存储
j ++;
}else{
pos = j - 1; // s中小数点后一位的位置
}
}
for(int i = 1; i <= n; ++ i) add(s, s);
// cout << s << endl << pos << endl;
// 四舍五入
if(s[pos] >= '5'){
string b(s.size(), '0');
b[pos + 1] = '1';
add(s, b);
for(int i = s.size() - 1; i > pos; -- i) cout << s[i];
}else{
for(int i = s.size() - 1; i > pos; -- i) cout << s[i];
}
return 0;
}
1 回复
0 转发
4 喜欢
12 阅读



