Golang 在数组中找到最大元素

Golang 在数组中找到最大元素

在本教程中,我们将学习如何编写一个Go语言程序来搜索数组中的最大元素。数组是一个用于存储连续内存位置上元素的变量。我们可以通过使用单独的函数或在main()函数中使用for循环和if条件来查找数组的最大元素。

在Main函数中找到数组中的最大元素

以下代码演示了如何搜索并找到数组中存在的最大元素。

步骤

步骤1 - 导入fmt包,该包允许我们在屏幕上打印任何内容。

步骤2 - 启动main函数。这是程序的可执行部分,从这里开始执行。

步骤3 - 初始化类型为int的变量temp、largestNumber和j。

步骤4 - 这些变量将在程序的后面用于保存初始和最大的数字。

步骤5 - 创建一个整数数组,并将值存储在其中,并使用fmt.Println()函数在屏幕上打印出来。

步骤6 - 现在使用for循环来迭代数组的每个元素,并使用if条件来检查当前数组元素是否大于之前存储的数字。

步骤7 - 如果找到的数字大于先前的数字,则将该数字存储在largestNumber变量中。

步骤8 - 升级temp计数,并将当前索引存储在int变量j中。

步骤9 - 对完整数组重复此过程。

步骤10 - 一旦过程结束,使用fmt.Println()函数将结果及元素的位置打印在屏幕上。

示例

在此程序中,我们使用for循环和条件语句来查找数组的最大元素。

package main
import "fmt"
func main() {
   var largestNumber, temp, j int
   arr := [5]int{100, -20, 300, 40, -50}
   fmt.Println("The unsorted array entered is:", arr)
   for i, element := range arr {
         if element > temp {
         temp = element
         largestNumber = temp
         j = i
      }
   }
   fmt.Println("Largest number of Array is ", largestNumber, "and its position is: ", j)
}

输出

The unsorted array entered is: [100 -20 300 40 -50]
Largest number of Array is  300 and its position is:  2

使用两个不同的函数找到数组中的最大数

现在让我们看看如何使用用户定义的函数来获取数组的最大元素。该函数接受一个整数数组作为参数,并返回最终结果,我们可以使用fmt.Println()函数将其存储并打印在屏幕上。

步骤

步骤 1 - 导入fmt包,允许我们在屏幕上打印任何内容。

步骤 2 - 创建一个名为findMaxElement()的函数。该函数返回数组中最大的值及其位置。

步骤 3 - 使用循环遍历数组以获取最大的整数值。

步骤 4 - 开始main()函数。

步骤 5 - 创建一个整数数组并向其存储值。使用fmt.Println()函数将数组打印在屏幕上。

步骤 6 - 通过将数组作为参数传递给findMaxElement()函数来调用该函数,并将结果存储在单独的变量中。

步骤 7 - 使用fmt.Println()函数将最大值及其位置打印在屏幕上。

步骤 8 - 通过获取更多的数组重复该过程。

示例

在这个示例中,我们将在main函数之外使用一个用户定义的函数。

package main
import "fmt"

// Creating a function called getLargestValue
func findMaxElement(arr []int) (int, int) {
   largestNumber := arr[0]
   var k int
   for i := 0; i < len(arr); i++ {
      if arr[i] > largestNumber {
         largestNumber = arr[i]
         k = i
      }
   }
   return largestNumber, k
}
func main() {
   arr := []int{1, 2, 3, 4, -5, -10}
   fmt.Println("The first array is:", arr)
   result, index := findMaxElement(arr)
   fmt.Println("The largest number of the array is: ", result, "and its position is:", index)
   fmt.Println()
   arr = []int{10, 8, 0, 20, 30}
   fmt.Println("The second array is:", arr)
   result, index = findMaxElement(arr)
   fmt.Println("The largest number of the array is: ", result, "and its position is:", index)
}

输出

The first array is: [1 2 3 4 -5 -10]
The largest number of the array is:  4 and its position is: 3

The second array is: [10 8 0 20 30]
The largest number of the array is:  30 and its position is: 4

结论

在本教程中,我们成功地执行了在数组中找到最大数的程序。在第一个示例中,我们将逻辑实现在程序的main()部分中,而在第二个示例中,我们使用了一个外部用户定义的函数来实现结果。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程