鸽子的浮点运算
模拟
就跟着题意模拟就好了
先读入,然后转成二进制,截断成 \(16\) 位,然后转成十进制 \(double\),最后计算,计算结果转成二进制截断成 \(16\) 位,然后输出
#include <iostream>
#include <cstdio>
#include <vector>
#include <string>
using namespace std;
typedef long long ll;
const ll mod = 1e9 + 7;
string fl_to_string(double x)
{
ll pre = (ll)x;
string now = "";
while(pre)
{
if(pre & 1) now = "1" + now;
else now = "0" + now;
pre >>= 1;
}
int f = now.size();
x -= (ll)x;
for(int i=0; i<50; i++)
{
x *= 2.0;
if(x >= 1) {now += "1"; x -= 1.0;}
else now += "0";
}
string ans = "0";
if(f)
{
ll cnt = f + 14;
string temp = "";
while(cnt)
{
if(cnt & 1) temp = "1" + temp;
else temp = "0" + temp;
cnt >>= 1;
}
while(temp.size() < 5) temp = "0" + temp;
ans += temp;
ans += string(now, 1, 10);
}
else
{
ll way = 0;
while(now[way] == '0') way++;
ll cnt = 14 - way;
string temp = "";
while(cnt)
{
if(cnt & 1) temp = "1" + temp;
else temp = "0" + temp;
cnt >>= 1;
}
while(temp.size() < 5) temp = "0" + temp;
ans += temp;
ans += string(now, way + 1, 10);
}
return ans;
}
ll string_to_ll(const string &s, int l = 1, int r = 5)
{
ll ans = 0;
for(int i=l; i<=r; i++)
ans = ans * 2 + s[i] - '0';
return ans;
}
double string_to_fl(string s)
{
ll way = string_to_ll(s);
double ans = 1, res = 1.0;
for(int i=6; i<s.length(); i++)
{
res *= 0.5;
ans += res * (s[i] - '0');
}
for(int i=way; i<15; i++) ans /= 2.0;
for(int i=way; i>15; i--) ans *= 2.0;
return ans;
}
double f16(double x)
{
string now = fl_to_string(x);
return string_to_fl(now);
}
int main()
{
int t;
cin >> t;
while(t--)
{
int op;
double a, b;
cin >> op >> a >> b;
if(op == 1) cout << fl_to_string(a) << "\n";
else
{
double ans = 0;
double aa = f16(a), bb = f16(b);
if(op == 2) ans = aa + bb;
else ans = aa * bb;
cout << fl_to_string(ans) << "\n";
}
}
return 0;
}
标签:string,temp,浮点运算,ll,int,2020,ans,省赛,now
From: https://www.cnblogs.com/dgsvygd/p/16758858.html