2017-10-15 7 views
2

Pour une raison quelconque, je reçois le mauvais résultat de big int quand je teste l'égalité, même si le résultat du mod est réellement correct! Par exemple, je voudrais calculer 2015% 2 qui se traduit par 1.big int me donnant des résultats faux dans l'égalité

Lorsque j'utilise grand int, je reçois faux quand je fais ceci:

fmt.Println((test.Mod(big.NewInt(2015),big.NewInt(2)))==big.NewInt(1)) 

Cependant, quand j'utilise int régulière, Je reçois vrai (ce qui est la bonne chose en tout cas):

fmt.Println(2015%2==1) 

Suis-je censé faire l'égalité différemment lors de l'utilisation grand int?

Répondre

1

Package big

import "math/big" 

func NewInt

func NewInt(x int64) *Int 

NewInt alloue et renvoie une nouvelle Int réglé sur x.

func (*Int) Cmp

func (x *Int) Cmp(y *Int) (r int) 

Cmp compare x et y et retourne:

-1 if x < y 
0 if x == y 
+1 if x > y 

Les variables a et b sont des pointeurs: *big.Int. Utilisez la méthode Cmp pour comparer les valeurs. Par exemple,

package main 

import (
    "fmt" 
    "math/big" 
) 

func main() { 
    a := big.NewInt(42) 
    fmt.Printf("a: %[1]T %[1]p %[1]v\n", a) 
    b := big.NewInt(42) 
    fmt.Printf("b: %[1]T %[1]p %[1]v\n", b) 
    fmt.Println("pointers:", a == b)  // compare pointers 
    fmt.Println("values: ", a.Cmp(b) == 0) // compare values 

    fmt.Println() 
    test := new(big.Int) 
    fmt.Println((test.Mod(big.NewInt(2015), big.NewInt(2))).Cmp(big.NewInt(1)) == 0) 
} 

Playground: https://play.golang.org/p/TH6UzceZ4y

Sortie:

a: *big.Int 0x1040a0c0 42 
b: *big.Int 0x1040a0d0 42 
pointers: false 
values: true 

true 
0

Regardez la fonction Cmp (* int).

package main 

import (
    "fmt" 
    "math/big" 
) 

func main() { 
    a := big.NewInt(5) 
    b := big.NewInt(5) 
    fmt.Println(a == b) 
    fmt.Println(a.Cmp(b)) 
}