本来想写一个大浮点数类,后来因为时间关系,只将浮点除法写了.其实除了除法有点难度外,加减乘均可借鉴
大整数类.
代码写得比较乱,因为时间比较急.
Code
1#include "BigInteger.h"
2#include <iostream>
3using namespace std;
4
5class BigDecimal
6{
7private:
8 BigInteger divide;
9 BigInteger divided;
10 int digit_count;
11
12 BigInteger Divide()
13 {
14 if(divide == BigInteger(0))
15 return BigInteger(0);
16 BigInteger result;
17
18 BigInteger temp(0), index(0), rest(0), zero(0);
19 BigInteger TEN(10);
20 int end = -1;
21 int start = divide.Length() - 1;
22 vector<int> quotients;
23
24 // BUG: How to deal when the divide can't divide divided?
25 while(rest != zero || start > end)
26 {
27 temp = rest * TEN;
28 digit_count = start > end ? digit_count : digit_count + 1;
29 temp = start > end ? temp + BigInteger((int)(divide[start])) : temp;
30 if(start <= end && temp < divided)
31 {
32 quotients.push_back(0);
33 }
34 while(temp < divided)
35 {
36 --start;
37 temp = start > end ? temp * TEN + BigInteger((int)(divide[start])) : temp * TEN;
38 digit_count = start > end ? digit_count : digit_count + 1;
39 if(start <= end && temp < divided)
40 {
41 quotients.push_back(0);
42 }
43 }
44 int quotient = 0;
45 rest = temp;
46 while(rest >= divided)
47 {
48 rest = rest - divided;
49 ++quotient;
50 }
51 quotients.push_back(quotient);
52 --start;
53 }
54 //--digit_count;
55
56 string r;
57 vector<int>::iterator i_end = quotients.end();
58 for(vector<int>::iterator ite = quotients.begin(); ite != i_end; ++ite)
59 {
60 r += (char)((*ite) + '0');
61 }
62 return BigInteger(r);
63 }
64
65public:
66 BigDecimal()
67 {
68 digit_count = 0;
69 divide = 0;
70 divided = 1;
71 }
72
73 BigDecimal(BigInteger a, BigInteger b)
74 {
75 digit_count = 0;
76 divide = a;
77 divided = b;
78 }
79
80 friend ostream & operator<<(ostream & os, BigDecimal & decimal)
81 {
82 BigInteger result = decimal.Divide();
83 int length = result.Length();
84 int copy_digit_count = decimal.digit_count;
85 if(copy_digit_count >= length)
86 os << "0.";
87 os << result;
88 return os;
89 }
90};
91
92void ConvertStringToBigInteger(string input, BigInteger & a, BigInteger & b)
93{
94 BigInteger EIGHT(8);
95 int dot_position = input.find_first_of('.');
96 int length = input.length();
97 int e_num = length - dot_position - 1;
98 b = EIGHT.Pow(e_num);
99 for(int i = dot_position + 1; i < length; ++i)
100 {
101 if(i == 0)
102 a = EIGHT * BigInteger((int)(input.at(i) - '0'));
103 else
104 a = a + BigInteger((int)(input.at(i) - '0')) * EIGHT.Pow(length - i - 1);
105 }
106}
107
108int _tmain(int argc, _TCHAR* argv[])
109{
110 string input;
111 while(cin >> input)
112 {
113 BigInteger a, b;
114 ConvertStringToBigInteger(input, a, b);
115 BigDecimal bd = BigDecimal(a, b);
116 cout << input << " [8] = " << bd << " [10]" << endl;
117 }
118 return 0;
119}
120
121
posted on 2009-03-31 21:21
肖羽思 阅读(491)
评论(0) 编辑 收藏 引用 所属分类:
ZOJ