简体   繁体   English

程序崩溃

[英]Program crashes

Program - 程序-

Function that accepts current year and the birth year, computes the age 接受当前年份和出生年份,计算年龄的函数

The problem - 问题 -

Program crashes 程序崩溃

The code- 编码-

int Age(int curr,  int birth)
{
if (curr > birth)
{
    return  1 + Age(curr--, birth);
}
return 0;
}

the input in function main is: 函数main中的输入为:

printf ("%d\n", Age(2014,1989)); 

Thanks for the help 谢谢您的帮助

It should be 它应该是

... Age(--curr, birth);

as curr shall be decremented before Age() is being called. 因为curr应该在调用Age()之前递减。

Using curr-- decrements curr The decrement applied to curr by curr-- takes effect after Age() returned, which will never happen, as the programm runs into a stack overflow due to trying infinit recursion. 使用 curr--递减 curr 应用于减量curr通过curr--后生效Age()返回,这将永远不会发生,因为PROGRAMM运行到堆栈溢出由于试图无穷远递归。

I guess this could be simply done as 我想这可以简单地完成

age = curr-birth-1

without worrying about recursion. 不用担心递归。

In curr-- you are doing post decremented, decrements will affect in next line. curr--您正在执行递减,递减会影响下一行。 so the value passed to function is always same as curr , You should do '--curr' so it will decrements curr value before calling of function. 因此,传递给函数的值始终与curr相同,您应该执行“ --curr”,这样它将在调用函数之前减小curr值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM