If you want to pass an array parameter to a function, you need to declare the parameter as an array when the function is defined. We can declare it intwo ways: The parameter sets the array size: The parameter does not set the array size: Let’s take a look at the following example, where the function takes an integer array parameter, and another parameter specifies the number of array elements and returns the average: Next let’s call this function: The output of the above example is as follows: The parameter we used in the above example does not set the array size. The floating point calculation output has a certain deviation, you can also convert the integer to set the precision. Set fixed precision: 2.31.1. Mode one #
void myFunction(param [10]int) { . . . }
2.31.2. Mode two #
void myFunction(param []int) { . . . }
2.31.3. Example #
Example #
func getAverage(arr []int, size int) float32 { var i int var avg, sum float32 for i = 0; i < size; ++i { sum += arr[i] } avg = sum / size return avg; }
Example #
package main import "fmt" func main() { /* Array length is 5 */ var balance = [5]int {1000, 2, 3, 17, 50} var avg float32 /* Array passed as a parameter to a function */ avg = getAverage( balance, 5 ) ; /* Output the average value returned */ fmt.Printf( "The average value is:%f ", avg ); } func getAverage(arr [5]int, size int) float32 { var i,sum int var avg float32 for i = 0; i < size;i++ { sum += arr[i] } avg = float32(sum) / float32(size) return avg; }
The average value is: 214.399994
Example #
package main import ( "fmt" ) func main() { a := 1.69 b := 1.7 c := a * b // The result should be 2.873 fmt.Println(c) // The output is 2.8729999999999998 }
Example #
package main import ( "fmt" ) func main() { a := 1690 // Represent 1.69 b := 1700 // Represent 1.70 c := a * b // The result should be 2873000 representing 2.873 fmt.Println(c) // internal code fmt.Println(float64(c) / 1000000) // display }