In this post, we will learn how to write a program to find the average of two numbers using the Go Programming language.
Average can be defined as the sum of values divided by the total number of terms
Since in this program we will be finding the average of two numbers, the total number of terms will be 2.
This Golang program asks the user to enter two numbers, then computes the average of those two numbers using the mathematical equation: Average = (a + b) / 2.
The average of two numbers is equal to the sum of two numbers divided by two.
Go Program to Find the Average of Two Numbers
package main import ( "fmt" ) func main() { var num1, num2, sum, avg float64 fmt.Print("Enter the first number: ") fmt.Scanln(&num1) fmt.Print("Enter the second number: ") fmt.Scanln(&num2) sum = num1 + num2 avg = sum / 2 fmt.Println("The average of the two numbers is = ", avg) }
Output
Enter the first number: 25 Enter the second number: 45 The average of the two numbers is = 35
How Does This Program Work?
var num1, num2, sum, avg float64
We have declared four float data type variables named num1, num2, sum, and avg.
fmt.Print("Enter the first number: ") fmt.Scanln(&num1) fmt.Print("Enter the second number: ") fmt.Scanln(&num2)
This example program asks the user to enter two integers. Here, the input is read using the fmt.Scan() method. The two integers entered by the user get stored in the num1 and num2 variables.
sum = num1 + num2 avg = sum / 2
The sum of two variables is calculated using the + operator, and the addition of num1 and num2 gets stored in the sum variable.
After that, the average is found by dividing the total sum by the total number of terms. The computed average gets stored in the avg-named variable.
fmt.Println("The average of two numbers is = ", avg)
At last, the average of two numbers is printed on the screen using the fmt.Print() method.
Conclusion
In this post, you learned how to write a program to find the average of two numbers using the Go Programming language.
If you have any doubts regarding the program, please leave your queries in the comment section.