凯发·k8国际娱乐网 it returns n * factorial(n-1). Iterative Factorial: The factorialIterative function uses a loop to calculate the factorial. It initializes result to 1 and multiplies it by each integer from
发布日期:2026-06-04 13:37    点击次数:163

Here's an example of implementing a simple mathematical function in Go凯发·k8国际娱乐网, specifically calculating the factorial of a number, which is a common example in higher mathematics:

Factorial Calculation in Go

go

package main import "fmt" // Function to calculate factorial recursivelyfunc factorial(n int) int { if n == 0 { return 1 } return n * factorial(n-1)} // Function to calculate factorial iterativelyfunc factorialIterative(n int) int { result := for i := 1; i <= n; i++ { result *= i } return result} func main() { num := 5 fmt.Printf("Factorial of %d (recursive): %d\n", num, factorial(num)) fmt.Printf("Factorial of %d (iterative): %d\n", num, factorialIterative(num))}

伸开剩余44%

Explanation:凯发·k8国际娱乐网

Recursive Factorial: The factorial function uses recursion to calculate the factorial of a number. If n is 0, it returns 1 (since 0! = 1). Otherwise, it returns n * factorial(n-1). Iterative Factorial: The factorialIterative function uses a loop to calculate the factorial. It initializes result to 1 and multiplies it by each integer from 1 to n. Main Function: The main function demonstrates both implementations by calculating the factorial of 5 and prin 发布于:辽宁省

热点资讯
相关资讯


Powered by 凯发·k8国际(中国)首页登录入口 @2013-2022 RSS地图 HTML地图

Copyright Powered by站群系统 © 2013-2024