版权声明:本人菜鸟一只,如文章有错误或您有高见,请不吝赐教 https://blog.csdn.net/qq_41138935/article/details/82730510
阶码为6,尾数为8的可表达最大的浮点数是0.111111111(2)*2^111111(2) 换算十进制为 0.998046875*2^63
而, 0.998046875*2^63=9.205357638345294*10^18
等价于 m*2^e=a*10^b 其中m为1-pow(2,-i-1),e为pow(2,j)-1,当i=8,j=6时,m*2^e得到0.998046875*2^63
两边取对数 log10(m)+e*log10(2)=log10(a)+b
当 temp= log10(m)+e*log10(2), temp=log10(a)+b 也成立, a,b为未知数,因为a<10,所以0<log10(a)<1
b=(int)temp,a=10^(temp-b),a为输入的9.205357638345294,b为18
代码如下:
#include<iostream>
#include<cstring>
#include<sstream>
#include<cmath>
using namespace std;
double a[15][35];
int b[15][35];
const double EPS=1e-5;
int main(){
string str;
double A;
int B;
//以0.998046875*2^63转化为9.205357638345294*10^18为例,对应的i=8,j=6 ,i对应尾数,j对应阶码
for(int i=0;i<10;i++){
for(int j=1;j<31;j++){
double a1=1-pow(2,-i-1); //十进制的尾数 0.998046875
double b1=pow(2,j)-1; //十进制的阶码 63
double temp=log10(a1)+b1*log10(2); // log10(0.998046875*2^63)=log10(0.998046875)+63*log10(2)
b[i][j]=(int)temp; //18
a[i][j]=pow(10,temp-b[i][j]); //9.205357638345294
}
}
while(cin>>str&&str!="0e0"){
str.replace(str.find('e'),1," ");
stringstream s(str);
s>>A>>B; //A为 9.205357638345294,B为18
bool flag=false;
for(int m=0;m<10;m++){
for(int e=1;e<31;e++){
if(b[m][e]==B&&fabs(A-a[m][e])<EPS){
cout<<m<<" "<<e<<endl;
flag=true;
break;
}
}
if(flag)
break;
}
}
return 0;
}