Octal Fractions
Description
Fractions in octal (base 8)
notation can be expressed exactly in decimal notation. For example,
0.75 in octal is 0.953125 (7/8 + 5/64) in decimal. All octal
numbers of n digits to the right of the octal point can be
expressed in no more than 3n decimal digits to the right of the
decimal point.
Write a program to convert octal numerals between 0 and 1, inclusive, into equivalent decimal numerals.
Write a program to convert octal numerals between 0 and 1, inclusive, into equivalent decimal numerals.
Input
The input to your program will
consist of octal numbers, one per line, to be converted. Each input
number has the form 0.d1d2d3 ... dk, where the di are octal digits
(0..7). There is no limit on k.
Output
Your output will consist of a
sequence of lines of the form
0.d1d2d3 ... dk [8] = 0.D1D2D3 ... Dm [10]
where the left side is the input (in octal), and the right hand side the decimal (base 10) equivalent. There must be no trailing zeros, i.e. Dm is not equal to 0.
where the left side is the input (in octal), and the right hand side the decimal (base 10) equivalent. There must be no trailing zeros, i.e. Dm is not equal to 0.
Sample Input
0.75 0.0001 0.01234567
Sample Output
0.75 [8] = 0.953125 [10] 0.0001 [8] = 0.000244140625 [10] 0.01234567 [8] = 0.020408093929290771484375[10]
题意: 8进制的小数转化为10进制的小数.
解题思路: (从网上学习的好方法)
1.每位数乘10然后对8取整(现在假设将p进制的小数转换为n进制,同样采用乘n取整:),
每转换一位,都必须从最低位s[len-1]开始至小数的最高位(即小数点后的一位),每次计算积
g=a[j]*n+k(其中k为下一位积的进位),本位进位数 k=g/p,积在本位存入 s[j]=g%p;
最后的整数k作为转换的一位存放于转换结果字符串中。
代码:
#include <cstdio>
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
// 小数任意进制转化
// 参数: s带转化的小数, p进制转化为n进制
string ss = "0123456789ABCDEF";
string change(string s, int p, int n)
{
int i, t, k, g, l, pos, len;
string str;
l = s.size();
pos = s.find(".");
len = 3*(l-pos-1);
t = 0;
str += "0.";
while(t < len)
{
k = 0;
t++;
for(i = l-1; i > pos; --i)
{
g = (s[i]-'0') * n + k;
k = int(g/p);
s[i] = g%p + '0';
}
str += ss.substr(k,1);
}
i = str.size()-1;
while(str[i] == '0') str[i] = '\0';
return str;
}
int main()
{
//freopen("input.txt","r",stdin);
string str;
while(cin >> str)
{
string result = change(str,8,10);
cout << str << " [8] = " << result << " [10]" << endl;
}
return 0;
}