1+ package main
2+
3+ import (
4+ "fmt"
5+ "github.com/shopspring/decimal"
6+ )
7+
8+ type Problem struct {
9+ Price decimal.Decimal
10+ Count decimal.Decimal
11+ MultiCount []decimal.Decimal
12+ }
13+
14+ func (problem * Problem ) Solve2 () []decimal.Decimal {
15+ result := []decimal.Decimal {}
16+
17+ for _ ,singleCount := range problem .MultiCount {
18+ singleResult := singleCount .Mul (problem .Price ).Round (2 )
19+ result = append (result ,singleResult )
20+ }
21+ return result
22+ }
23+
24+ func (problem * Problem ) CheckSolve (result []decimal.Decimal ){
25+ sum ,_ := decimal .NewFromString ("0" )
26+ for _ ,singleResult := range result {
27+ sum = sum .Add (singleResult )
28+ }
29+ total := problem .Price .Mul (problem .Count ).Round (2 )
30+ fmt .Printf ("\n solution: %v\n " ,result )
31+ if total .Cmp (sum ) != 0 {
32+ fmt .Printf ("solve fail: total %v != sum %v\n " ,total ,sum )
33+ }else {
34+ fmt .Printf ("solve success: total = %v\n " ,total )
35+ }
36+ }
37+
38+ func (problem * Problem )Solve () []decimal.Decimal {
39+ result := []decimal.Decimal {}
40+
41+ total := problem .Price .Mul (problem .Count ).Round (2 )
42+ count := problem .Count
43+
44+ for _ ,singleCount := range problem .MultiCount {
45+
46+ //计算当前的值
47+ precent := singleCount .Div (count )
48+ singleResult := precent .Mul (total ).Round (2 )
49+ result = append (result ,singleResult )
50+
51+ //取余额
52+ count = count .Sub (singleCount )
53+ total = total .Sub (singleResult )
54+ }
55+
56+ return result ;
57+ }
58+
59+ func NewProblem (price decimal.Decimal ,count decimal.Decimal , multiCount []decimal.Decimal ) * Problem {
60+ if price .Sign () < 0 {
61+ panic ("price can not be negative" )
62+ }
63+
64+ if count .Sign () < 0 {
65+ panic ("count can not be negative" )
66+ }
67+
68+ allCount ,_ := decimal .NewFromString ("0" )
69+ for _ ,it := range multiCount {
70+ if it .Sign () < 0 {
71+ panic ("multiCount can not be negative" )
72+ }
73+ allCount = allCount .Add (it )
74+ }
75+ if allCount .Cmp ( count ) != 0 {
76+ panic ("multi count sum != count" )
77+ }
78+ problem := & Problem {}
79+ problem .Price = price
80+ problem .Count = count
81+ problem .MultiCount = multiCount
82+ return problem
83+ }
84+
85+ func newDecimal (a string ) decimal.Decimal {
86+ re ,err := decimal .NewFromString (a )
87+ if err != nil {
88+ panic (err )
89+ }
90+ return re
91+ }
92+
93+ func main (){
94+ problem := NewProblem (
95+ newDecimal ("32.23" ),
96+ newDecimal ("10.12" ),
97+ []decimal.Decimal {newDecimal ("0.01" ),newDecimal ("0.01" ),newDecimal ("10.1" )},
98+ )
99+
100+ //分摊法
101+ result1 := problem .Solve ()
102+ problem .CheckSolve (result1 )
103+
104+ //原始法
105+ result2 := problem .Solve2 ()
106+ problem .CheckSolve (result2 )
107+ }
0 commit comments