编写一个 Go 程序,使用数组和 For 循环计算给定金额中的总货币钞票数。首先,我们声明一个包含可用钞票的整数数组。接下来,我们使用 for 循环(for i := 0; i < 8; i++)迭代钞票数组,并用每个数组项除以金额。然后,我们通过从原始金额中减去该现金金额来更新计数。
package main
import "fmt"
func main() {
notes := [8]int{500, 100, 50, 20, 10, 5, 2, 1}
var amount int
fmt.Print("Enter the Total Amount of Cash = ")
fmt.Scanln(&amount)
temp := amount
for i := 0; i < 8; i++ {
fmt.Println(notes[i], " Notes = ", temp/notes[i])
temp = temp % notes[i]
}
}
Enter the Total Amount of Cash = 5698
500 Notes = 11
100 Notes = 1
50 Notes = 1
20 Notes = 2
10 Notes = 0
5 Notes = 1
2 Notes = 1
1 Notes = 1
Go 程序使用函数计算总钞票数
在此 Golang 程序中,我们创建了一个(countingNotes(amount int))函数,该函数计算并打印给定现金中的货币钞票数。
package main
import "fmt"
func countingNotes(amount int) {
notes := [8]int{500, 100, 50, 20, 10, 5, 2, 1}
temp := amount
for i := 0; i < 8; i++ {
fmt.Println(notes[i], " Notes = ", temp/notes[i])
temp = temp % notes[i]
}
}
func main() {
var amount int
fmt.Print("Enter the Total Amount of Cash = ")
fmt.Scanln(&amount)
countingNotes(amount)
}
