这个程序出现了堆栈溢出的问题,我不确定原因是什么。

huangapple go评论71阅读模式
英文:

This program is stack overflowing and I am not sure why

问题

我不会直接运行代码,但是我可以帮你翻译代码的内容。这段代码是一个计算超级蛋糕的函数。它接受两个整数参数n和k,并返回一个整数结果。

这段代码定义了一个名为hypercake的函数,它使用了一个名为combinations的嵌套函数来计算组合数。combinations函数接受两个整数参数n和r,并返回一个整数结果。

hypercake函数中,首先定义了一个变量sum,并初始化为0。然后进行一系列条件判断和计算,最终返回计算结果。

main函数中,首先声明了两个整数变量n和k。然后通过用户输入来获取n和k的值。接下来调用hypercake函数,并将结果赋给变量ans。最后打印出ans的值。

根据你的描述,代码可能存在溢出的问题。你可以尝试使用更大的数据类型来存储计算结果,例如使用int64代替int。另外,你也可以检查一下计算过程中是否存在其他错误。

英文:

I had to write the following for a programming assignment and after running the code and giving input from the user it overflows.

package main

import (
	"fmt"
)

func hypercake(n int, k int) int {
	combinations := func(n int, r int) int {
		var factorial func(int) int
		factorial = func(n int) int {
			if n < 0 {
				fmt.Print("Cannot take the factorial of a negative number.")
				return -1
			} else if n == 0 {
				return 1
			} else {
				return factorial(n) * factorial(n-1)
			}
		}

		if r >= 0 && r <= n {
			ans := factorial(n) / (factorial(r) * factorial(n-r))
			return ans
		} else {
			fmt.Print("Something was wrong with input")
			return -1
		}
	}

	sum := 0
	if k > 0 {
		if k == 1 {
			return 1
		} else {
			for i := 0; i <= k; i++ {
				sum += combinations(n, i)
			}
		}
		return sum
	} else {
		fmt.Print("You must have a postive number of dimensions")
		return -1
	}
}

func main() {
	var n, k int
	fmt.Print("Type how many cuts in your cake.")
	fmt.Scan(&n)
	fmt.Print("Type how many dimensions in your cake.")
	fmt.Scan(&k)
	ans := hypercake(n, k)
	fmt.Print(ans)
}

I have tried using very small inputs because I thought that it was just exceeding the bounds for a n int and that did not work.

答案1

得分: 3

我觉得你不理解阶乘的概念。
考虑 n! = n * (n - 1) * (n - 2) ... 你明白了吧。
它的公式是 f(n) = n * f(n - 1)。

但是你的实现方式是:
f(n) = f(n) * f(n - 1)
最终你会用相同的参数调用相同的函数,导致堆栈溢出。

我建议你将

return factorial(n) * factorial(n-1)

改为

return n * factorial(n-1)

希望对你有所帮助!

英文:

It seems to me that you don't understand factorial.
Consider n! = n * (n - 1) * (n - 2) ... you get the idea.
It is f(n) = n * f(n - 1)

But you implement factorial as:
f(n) = f(n) * f(n - 1)
You ultimately end up calling the same function with the same arguments you've taken - hence the stack overflow.

I would recomend that you change

return factorial(n) * factorial(n-1)

to

return n * factorial(n-1)

Hope this helps!

huangapple
  • 本文由 发表于 2022年4月2日 10:36:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/71714448.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定