modernc.org/gc@v1.0.1-0.20240304020402-f0dba7c97c2b/testdata/errchk/test/ken/cplx4.go (about)

     1  // run
     2  
     3  // Copyright 2010 The Go Authors. All rights reserved.
     4  // Use of this source code is governed by a BSD-style
     5  // license that can be found in the LICENSE file.
     6  
     7  // Test complex numbers,including fmt support.
     8  // Used to crash.
     9  
    10  package main
    11  
    12  import "fmt"
    13  
    14  const (
    15  	R = 5
    16  	I = 6i
    17  
    18  	C1 = R + I // ADD(5,6)
    19  )
    20  
    21  func want(s, w string) {
    22  	if s != w {
    23  		panic(s + " != " + w)
    24  	}
    25  }
    26  
    27  func doprint(c complex128, w string) {
    28  	s := fmt.Sprintf("%f", c)
    29  	want(s, w)
    30  }
    31  
    32  func main() {
    33  
    34  	// constants
    35  	s := fmt.Sprintf("%f", -C1)
    36  	want(s, "(-5.000000-6.000000i)")
    37  	doprint(C1, "(5.000000+6.000000i)")
    38  
    39  	// variables
    40  	c1 := C1
    41  	s = fmt.Sprintf("%f", c1)
    42  	want(s, "(5.000000+6.000000i)")
    43  	doprint(c1, "(5.000000+6.000000i)")
    44  
    45  	// 128
    46  	c2 := complex128(C1)
    47  	s = fmt.Sprintf("%G", c2)
    48  	want(s, "(5+6i)")
    49  
    50  	// real, imag, complex
    51  	c3 := complex(real(c2)+3, imag(c2)-5) + c2
    52  	s = fmt.Sprintf("%G", c3)
    53  	want(s, "(13+7i)")
    54  
    55  	// compiler used to crash on nested divide
    56  	c4 := complex(real(c3/2), imag(c3/2))
    57  	if c4 != c3/2 {
    58  		fmt.Printf("BUG: c3 = %G != c4 = %G\n", c3, c4)
    59  		panic(0)
    60  	}
    61  }