我想实现下面显示的界面。我不知道如何开始。有人能告诉我应该如何实现这些功能吗?
package interval
package main
type Interval interface {
contains(r float64) bool // if r is in x, then true
average(Y Intervall) (Intervall, error)
String() string //cast interval"[a,b]" to [a,b]
completecontains(Y Intervall) bool //if y is completely in x, give true
New(a, b float64) Intervall
//var a int
}
type Complex struct {
first int
}
func (c Complex) contains(r float64) bool {
if a <= r <= b {
return true
} else {
return false
}
}
func (c Complex) String() string {
return "a"
}
func (c Complex) length() float64 {
return 2.3
}
func main() {
}
答案 0 :(得分:0)
我无法真正告诉你在这里尝试做什么,但代码存在一些问题
可能不是你想要的,但它现在编译并运行(但由于main是空的,所以没有做任何事情)
package main
//import "fmt"
type Intervall interface {
contains(r float64) bool // if r is in x, then true
average(Y Intervall) (Intervall, error)
String() string //cast interval"[a,b]" to [a,b]
completecontains(Y Intervall) bool //if y is completely in x, give true
New(a, b float64) Intervall
}
type Complex struct {
first int
a float64
b float64
}
func (c Complex) contains(r float64) bool {
if c.a <= r && r <= c.b {
return true
} else {
return false
}
}
func (c Complex) String() string {
return "a"
}
func (c Complex) length() float64 {
return 2.3
}
func main() {
}
答案 1 :(得分:0)
不确定为什么具体间隔被称为“复杂”或两个间隔的平均值可能是什么,但这是我能得到的尽可能接近。此外,不确定使用界面的好处是什么。
http://play.golang.org/p/sxFRkJZCFa
package main
import "fmt"
type Interval interface {
Contains(r float64) bool
Average(y Interval) (Interval, error)
String() string
CompletelyContains(y Interval) bool
CompletelyContainedBy(y Interval) bool
}
type Complex struct {
a, b float64
}
func (c Complex) Contains(r float64) bool {
return c.a <= r && r <= c.b
}
func (c Complex) Average(y Interval) (Interval, error) {
return nil, fmt.Errorf("What the heck is the average of two intervals?")
}
func (c Complex) CompletelyContains(y Interval) bool {
return y.CompletelyContainedBy(c)
}
func (c Complex) CompletelyContainedBy(y Interval) bool {
return y.Contains(c.a) && y.Contains(c.b)
}
func (c Complex) String() string {
return fmt.Sprintf("[%v,%v]", c.a, c.b)
}
func main() {
var x Interval = Complex{a: 1, b: 5.1}
var y Interval = Complex{a: 1.3, b: 5}
fmt.Println("x contains 3:", x.Contains(3))
fmt.Println("x completely contains y:", x.CompletelyContains(y))
avg, err := x.Average(y)
fmt.Println("Average of x and y:", avg, "with error:", err)
fmt.Println("x:", x)
}
编辑:这是一种以您希望的方式实施“平均”的复杂方式。复杂性来自于避免直接访问y.a和y.b,这会破坏使用接口的目的(如果有的话)。