使用 for 循环编写一个 Go 程序来查找数字的各位数字之积。for 循环条件保持数字大于零。在循环中,
- prodReminder = prodNum % 10 -> 返回数字的最后一位数字。
- product = product * prodReminder -> 将最后一位数字与 product 相乘。
- prodNum = prodNum / 10 – 它会从 prodNum 中移除最后一位数字。
package main
import "fmt"
func main() {
var prodNum, product, prodReminder int
fmt.Print("Enter the Number to find the Digits Product = ")
fmt.Scanln(&prodNum)
for product = 1; prodNum > 0; prodNum = prodNum / 10 {
prodReminder = prodNum % 10
product = product * prodReminder
}
fmt.Println("The Product of Digits in this Number = ", product)
}

Go 程序使用函数查找数字的各位数字之积
package main
import "fmt"
var product int
func digitsProduct(prodNum int) int {
var prodReminder int
for product = 1; prodNum > 0; prodNum = prodNum / 10 {
prodReminder = prodNum % 10
product = product * prodReminder
}
return product
}
func main() {
var prodNum int
fmt.Print("Enter the Number to find the Digits Product = ")
fmt.Scanln(&prodNum)
product = digitsProduct(prodNum)
fmt.Println("The Product of Digits in this Number = ", product)
}
SureshMac:GoExamples suresh$ go run digitsProd2.go
Enter the Number to find the Digits Product = 879
The Product of Digits in this Number = 504
SureshMac:GoExamples suresh$ go run digitsProd2.go
Enter the Number to find the Digits Product = 45
The Product of Digits in this Number = 20
此 Golang 程序通过递归调用 digitsProduct(prodNum / 10) 函数来计算数字的各位数字之积。
package main
import "fmt"
var product int = 1
func digitsProduct(prodNum int) int {
if prodNum <= 0 {
return 0
}
product = product * (prodNum % 10)
digitsProduct(prodNum / 10)
return product
}
func main() {
var prodNum int
fmt.Print("Enter the Number to find the Digits Product = ")
fmt.Scanln(&prodNum)
product = digitsProduct(prodNum)
fmt.Println("The Product of Digits in this Number = ", product)
}
SureshMac:GoExamples suresh$ go run digitsProd3.go
Enter the Number to find the Digits Product = 4789
The Product of Digits in this Number = 2016
SureshMac:GoExamples suresh$ go run digitsProd3.go
Enter the Number to find the Digits Product = 22457
The Product of Digits in this Number = 560