Introduction
In geometry, the hypotenuse is the longest side of a right-angled triangle, opposite the right angle. The length of the hypotenuse can be calculated using the well-known Pythagorean theorem, which states that the square of the hypotenuse is equal to the sum of the squares of the other two sides.
Objective
The objective of this program is to demonstrate how to calculate the length of the hypotenuse of a right-angled triangle given the lengths of the other two sides. The program will use the Pythagorean theorem to calculate the hypotenuse.
Go Program Code
package main import ( "fmt" "math" ) // Function to calculate the hypotenuse func calculateHypotenuse(a, b float64) float64 { return math.Sqrt(a*a + b*b) } func main() { var sideA, sideB float64 // Taking user input for sides a and b fmt.Print("Enter the length of side a: ") fmt.Scanln(&sideA) fmt.Print("Enter the length of side b: ") fmt.Scanln(&sideB) // Calculating the hypotenuse hypotenuse := calculateHypotenuse(sideA, sideB) // Output the result fmt.Printf("The length of the hypotenuse is: %.2f\n", hypotenuse) }
Program Explanation
This Go program begins by importing the necessary packages. We use the math package for the math.Sqrt
function, which calculates the square root. The program consists of the following main parts:
- Imports: The program imports the
fmt
package for input/output operations and themath
package to use the square root function. - calculateHypotenuse Function: This function takes two
float64
values (representing the sides of the triangle), calculates the sum of their squares, and returns the square root of that sum, which gives the length of the hypotenuse. - User Input: The program prompts the user to input the lengths of the two sides,
a
andb
. - Hypotenuse Calculation: After taking the input, the program calls the
calculateHypotenuse
function and stores the result in thehypotenuse
variable. - Output: Finally, the program outputs the calculated length of the hypotenuse with two decimal places.
How to Run the Program
To run this Go program, follow these steps:
-
- Ensure that Go is installed on your system. You can download it from the official website: Go Downloads.
- Save the program code in a file with the extension
.go
, e.g.,hypotenuse.go
. - Open a terminal or command prompt, navigate to the directory where the file is saved, and run the following command to execute the program:
go run hypotenuse.go
- The program will prompt you to enter the lengths of sides
a
andb
and will then display the length of the hypotenuse.