编写Golang程序以查找数组中元素的频率
例子
在输入数组中,arr=[2、4、6、7、8、1、2]
给定数组中2的频率为2
7的频率为1
3的频率为0。
解决这个问题的方法
步骤1:定义一个接受数组和数字的函数
步骤2:声明一个变量count=0。
步骤3:迭代给定数组,如果在数组中出现num,则将计数增加1。
步骤4:打印给定num的计数。
程序
package main
import "fmt"
func findFrequency(arr []int, num int){
count := 0
for _, item := range arr{
if item == num{
count++
}
}
fmt.Printf("Frequency of %d in given array is %d.\n", num, count)
}
func main(){
findFrequency([]int{2, 4, 5, 6, 3, 2, 1}, 2)
findFrequency([]int{0, 1, 3, 1, 6, 2, 1}, 1)
findFrequency([]int{1, 2, 3, 4, 5, 6, 7}, 10)
}输出结果Frequency of 2 in given array is 2. Frequency of 1 in given array is 3. Frequency of 10 in given array is 0.
热门推荐
10 感谢韩语老师祝福语简短
11 升职文案高级祝福语简短
12 花童结婚祝福语大全简短
13 向国庆送祝福语简短
14 什么寄语简短祝福语女生
15 客户回礼祝福语大全简短
16 女孩生日祝福语简短创意
17 家长回复节日祝福语简短
18 给外婆敬酒祝福语简短