面试题答案
一键面试package main
import (
"fmt"
"math"
)
// 定义Shape接口
type Shape interface {
Area() float64
}
// 定义Rectangle结构体
type Rectangle struct {
Width float64
Height float64
}
// Rectangle实现Shape接口的Area方法
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}
// 定义Circle结构体
type Circle struct {
Radius float64
}
// Circle实现Shape接口的Area方法
func (c Circle) Area() float64 {
return math.Pi * c.Radius * c.Radius
}
// 定义CalculateArea函数
func CalculateArea(s Shape) float64 {
return s.Area()
}
你可以使用以下方式调用:
func main() {
rectangle := Rectangle{Width: 5, Height: 3}
circle := Circle{Radius: 4}
fmt.Printf("Rectangle Area: %.2f\n", CalculateArea(rectangle))
fmt.Printf("Circle Area: %.2f\n", CalculateArea(circle))
}
以上代码使用Go语言实现,定义了Shape
接口以及Rectangle
和Circle
结构体来实现该接口的Area
方法,并编写了CalculateArea
函数来计算不同图形的面积。如果是其他编程语言,实现方式会有所不同,例如Java实现如下:
interface Shape {
double Area();
}
class Rectangle implements Shape {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
public double Area() {
return width * height;
}
}
class Circle implements Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double Area() {
return Math.PI * radius * radius;
}
}
class AreaCalculator {
public static double CalculateArea(Shape s) {
return s.Area();
}
}
调用方式如下:
public class Main {
public static void main(String[] args) {
Rectangle rectangle = new Rectangle(5, 3);
Circle circle = new Circle(4);
System.out.printf("Rectangle Area: %.2f\n", AreaCalculator.CalculateArea(rectangle));
System.out.printf("Circle Area: %.2f\n", AreaCalculator.CalculateArea(circle));
}
}
上述Java代码定义了Shape
接口,Rectangle
和Circle
类实现该接口,并提供了CalculateArea
方法计算面积。这里以Go和Java为例展示了不同语言对该需求的实现方式。