File tree Expand file tree Collapse file tree 2 files changed +64
-0
lines changed Expand file tree Collapse file tree 2 files changed +64
-0
lines changed Original file line number Diff line number Diff line change 1+ package problem11 ;
2+
3+ /**
4+ * 求数值的整数次方
5+ * 需要考虑的边界条件:
6+ * 1. 0的0次方
7+ * 2. exponent为负数
8+ * 3. double的精度问题
9+ * Created by bjyangrubing on 2016/8/16.
10+ */
11+ public class Power
12+ {
13+ public double power (double base , int exponent ) throws Exception
14+ {
15+ double result = 0.0 ;
16+ if (equal (base , 0.0 ) && exponent < 0 )
17+ throw new Exception ("0的负数次幂无意义" );
18+ if (equal (exponent , 0 ))
19+ return 1.0 ;
20+ if (exponent < 0 )
21+ {
22+ result = powerWithExponent (1.0 / base , -exponent );
23+ }
24+ else
25+ {
26+ result = powerWithExponent (base , exponent );
27+ }
28+ return result ;
29+ }
30+
31+ private double powerWithExponent (double base , int exponent )
32+ {
33+ double result = 1.0 ;
34+ for (int i = 0 ; i < exponent ; i ++)
35+ {
36+ result *= base ;
37+ }
38+ return result ;
39+ }
40+
41+ public boolean equal (double base , double v )
42+ {
43+ if ((base - v > -0.0000001 ) && (base - v < 0.0000001 ))
44+ return true ;
45+ return false ;
46+ }
47+
48+ }
Original file line number Diff line number Diff line change 1+ package problem11 ;
2+
3+ import org .junit .Test ;
4+
5+ /**
6+ * Created by bjyangrubing on 2016/8/16.
7+ */
8+ public class PowerTest
9+ {
10+ @ Test
11+ public void test () throws Exception
12+ {
13+ Power power = new Power ();
14+ System .out .println (power .equal (power .power (2 , 4 ), 16 ));
15+ }
16+ }
You can’t perform that action at this time.
0 commit comments