我试图用递归函数计算y= (1 +4+7+. 301) / (2 +5+8+.+ 272)表达式,但我写的内容不起作用。有人能告诉我我做错了什么吗?此版本返回退出代码-1073741571 (0xC00000FD)完成的错误>进程。
这是我的密码
int calcSum(int start, int end, int steep){
if(start == 0){
return 0;
} else{
return start + calcSum(start,end,steep);
}
}
int main() {
printf("y = %d", calcSum(1,301,3)/ calcSum(1,272,3));
return 0;
}发布于 2022-05-16 08:48:11
问题在于递归调用,您没有做任何事情来确保函数停止调用并因此中断。当您说要递归地添加数字时,您需要做三件事:调用相同的函数(显然),具有终止条件,在本例中实际上传递值,以便在每个调用中按照所需的顺序添加。
#include <stdio.h>
int calcSum(int start, int end, int steep){
// Stop calling once you have added all numbers
if(start<=end){
return start + calcSum(start+steep,end,steep); // increment start with steep so that in each call the next term in the sequence is added.
}
else return 0; //return 0 after start > end as we don't need to add after that.
}
int main(void) {
printf("y = %d", calcSum(1,301,3)/ calcSum(2,272,3));
return 0;
}下面是工作代码的样子。
https://stackoverflow.com/questions/72255790
复制相似问题