poj1131

View Code
   
     
1 /* 给定一个八进制的小数题目要求你把它转换为十进制小数,转换后小数的位数是转换前八进制小
数位数的3倍且不输出末尾无意义的零(即后置零).
我采用的方法是乘10然后对8取整(现在假设将p进制的小数转换为n进制,
同样采用乘n取整:),每转换一位,都必须从最低位s[len-1]开始至小数的最高位(即小数点后的一位),
每次计算积 g=a[j]*n+k(其中k为下一位积的进位),本位进位数 k=g/p,积在本位存入
s[j]=g%p;最后的整数k作为转换的一位存放于转换结果字符串中。 */
2 #include " iostream "
3 #include " math.h "
4 using namespace std;
5 char ch[ 100 ];
6 int ww[ 100 ],pp = 0 ;
7 int a[ 100 ],b[ 100 ],c[ 100 ],d[ 100 ],w[ 100 ],R[ 100 ],RR[ 100 ];
8 int i ,j,L,t,s;
9 int main()
10 {
11 while (scanf( " %s " , & ch) != EOF)
12 {
13 pp = 0 ;
14 memset(c, 0 , sizeof (c));
15 memset(a, 1 , sizeof (a));
16 memset(w, 0 , sizeof (w));
17 memset(R, 0 , sizeof (R));
18 L = strlen(ch);
19 int sign = 0 ;
20 for (i = 0 ;i < L;i ++ )
21 if (ch[i] == ' . ' ) { sign = i; break ; }
22 int k = 0 ;
23 for (i = L - 1 ;i > sign;i -- )
24 a[k ++ ] = ch[i] - ' 0 ' ;
25
26 int flag = 0 ;
27 t = 1 ; c[ 0 ] = 1 ;
28 s = 0 ;
29 // ************求0.125~n*************
30 for ( int p = k - 1 ;p >= 0 ;p -- )
31 {
32 for (j = 0 ;j < t;j ++ )
33 {
34 int sum = 125 * c[j] + flag;
35 c[j] = sum % 10 ;
36 flag = sum / 10 ;
37 }
38 while (flag)
39 {
40 c[t ++ ] = flag % 10 ;
41 flag /= 10 ;
42 }
43 int mark = 0 ;
44 // ********************************
45 for ( int q = 0 ;q < t;q ++ )
46 {
47 int mul = a[p] * c[q] + mark;
48 d[s ++ ] = mul % 10 ;
49 mark = mul / 10 ;
50 }
51
52 int ii,jj;
53 for (ii = 0 ;ii < p * 3 ;ii ++ ) // 增加0的个数,3表示每乘一次得三位小数
54 w[ii] = 0 ;
55
56 for (jj = 0 ;jj < t;jj ++ )
57 w[ii ++ ] = d[jj]; // 将所有的数保存在w[]中
58
59 s = 0 ;
60
61 ww[pp ++ ] = ii; // 长度相等
62 for (i = ii;i < ww[ 0 ];i ++ )
63 w[i] = 0 ;
64
65 int Flag = 0 ;
66 for (i = 0 ;i < ww[ 0 ];i ++ )
67 {
68 int sum = w[i] + R[i] + Flag;
69 RR[i] = sum % 10 ;
70 Flag = sum / 10 ;
71 }
72 if (Flag == 1 ) RR[i ++ ] = Flag;
73 for ( int xx = 0 ;xx < i;xx ++ )
74 R[xx] = RR[xx];
75 }
76 printf( " %s [8] = " ,ch);
77 printf( " 0. " );
78 int sign11 = 0 ;
79
80 for (i = 0 ;i < ww[ 0 ];i ++ )
81 if (RR[i] != 0 ) {sign11 = i; break ;}
82 for (i = ww[ 0 ] - 1 ;i >= sign11;i -- )
83 printf( " %d " ,RR[i]);
84 printf( " [10]\n " );
85 }
86 return 0 ;
87 }

你可能感兴趣的:(poj)