八进制浮点数转十进制浮点数。
直接转有点麻烦,因为会同时涉及到乘法和除法。我的做法是先转成二进制再转十进制。八进制转二进制非常简单,二进制转十进制则无需做乘法(乘1或者乘0)。
Accepted | 1086 | C++ | 00:00.00 | 388K |
#include<stdio.h>
#include <string.h>
const char list[8][4] = {"000","001","010","011","100","101","110","111" };
void add(char a[],char b[])
{
int lena = strlen(a);
int lenb = strlen(b);
int c = 0 ;
int len = lena >= lenb ? lena : lenb;
for(int i = lena; i < len; a[i] = b[i],i++ );
len = lena >= lenb ? lenb : lena;
while(--len > 1 )
{
int temp = a[len] + b[len] - '0' * 2 + c;
a[len] = temp % 10 + '0' ;
c = temp / 10 ;
}
}
void div2(char num[])
{
if(num[0] == '1' )
{
num[0] = '0',num[1] = '.',num[2] = '5' ;
return ;
}
int i = 1,r = 0 ;
while(num[++i] == '0' );
for(; num[i]; i++ )
{
int temp = 10 * r + num[i] - '0' ;
num[i] = temp / 2 + '0' ;
r = temp % 2 ;
}
num[i] = '5' ;
}
void solve(char num[])
{
char bnum[60] = "" ;
int i;
for(i = 2; num[i]; i++ )
bnum[(i - 2) * 3] = list[num[i] - '0'][0 ],
bnum[(i - 2) * 3 + 1] = list[num[i] - '0'][1 ],
bnum[(i - 2) * 3 + 2] = list[num[i] - '0'][2 ];
char flag[50] = "1" ;
char res[50] = "0.0" ;
i = 0 ;
while (bnum[i])
{
div2(flag);
if(bnum[i++] == '1' ) add(res,flag);
}
printf("%s [8] = %s [10]/n" ,num,res);
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("1086.txt","r" ,stdin);
#endif
char num[20 ];
while(scanf("%s",num) != EOF)
solve(num);
#ifndef ONLINE_JUDGE
fclose(stdin);
#endif
return 0 ;
}
#include <string.h>
const char list[8][4] = {"000","001","010","011","100","101","110","111" };
void add(char a[],char b[])
{
int lena = strlen(a);
int lenb = strlen(b);
int c = 0 ;
int len = lena >= lenb ? lena : lenb;
for(int i = lena; i < len; a[i] = b[i],i++ );
len = lena >= lenb ? lenb : lena;
while(--len > 1 )
{
int temp = a[len] + b[len] - '0' * 2 + c;
a[len] = temp % 10 + '0' ;
c = temp / 10 ;
}
}
void div2(char num[])
{
if(num[0] == '1' )
{
num[0] = '0',num[1] = '.',num[2] = '5' ;
return ;
}
int i = 1,r = 0 ;
while(num[++i] == '0' );
for(; num[i]; i++ )
{
int temp = 10 * r + num[i] - '0' ;
num[i] = temp / 2 + '0' ;
r = temp % 2 ;
}
num[i] = '5' ;
}
void solve(char num[])
{
char bnum[60] = "" ;
int i;
for(i = 2; num[i]; i++ )
bnum[(i - 2) * 3] = list[num[i] - '0'][0 ],
bnum[(i - 2) * 3 + 1] = list[num[i] - '0'][1 ],
bnum[(i - 2) * 3 + 2] = list[num[i] - '0'][2 ];
char flag[50] = "1" ;
char res[50] = "0.0" ;
i = 0 ;
while (bnum[i])
{
div2(flag);
if(bnum[i++] == '1' ) add(res,flag);
}
printf("%s [8] = %s [10]/n" ,num,res);
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("1086.txt","r" ,stdin);
#endif
char num[20 ];
while(scanf("%s",num) != EOF)
solve(num);
#ifndef ONLINE_JUDGE
fclose(stdin);
#endif
return 0 ;
}