find the volume of a cone in go

To find the volume of a cone in Go, you need to use its mathematical formula which is:

V = (1/3) * π * r² * h

Where V is the volume, π is a mathematical constant approximately equal to 3.14, r is the radius of the base of the cone, and h is the height of the cone.

You can use the math package in Go to access the value of π and compute the volume of the cone. Here's an example implementation:

main.go
package main

import (
	"fmt"
	"math"
)

func coneVolume(r float64, h float64) float64 {
	return (1.0 / 3.0) * math.Pi * math.Pow(r, 2) * h
}

func main() {
	var radius, height float64

	fmt.Println("Enter the radius of the cone: ")
	fmt.Scanln(&radius)

	fmt.Println("Enter the height of the cone: ")
	fmt.Scanln(&height)

	volume := coneVolume(radius, height)

	fmt.Printf("The volume of the cone is: %.2f", volume)
}
420 chars
25 lines

In this example, we define a function coneVolume which takes in the radius and height of the cone and computes its volume using the formula mentioned above. We use math.Pi from the math package to get the value of π and math.Pow to compute the square of the radius.

In the main function, we take user input for the radius and height of the cone, compute its volume using the coneVolume function, and print out the result with 2 decimal places using %.2f format specifier.

related categories

gistlibby LogSnag