简体   繁体   English

如何确保递归终止?

[英]How can I make sure that the recursion terminates?

In this Example the function terminates in a strange way, although the values don't change (no base case is reached)在这个例子中,function 以一种奇怪的方式终止,尽管值没有改变(没有达到基本情况)

#include<stdio.h>


int power(int a, int b);


int main(){

    int a;
    int b;
    printf(" Enter number: ");
    scanf(" %d",&a);
    printf(" Enter it's power: ");
    scanf( " %d",&b);
    printf("\n\n Result: %d",power(a,b));
}

int power(int a, int b){

    if( b == 0)
    return 1;
    if ( a == 0)
    return 0;
    if ( b == 1)
    return a;
    else return a*(b,a); //shouldn't it be: "else return a*(a,b-1);" , how does this work!
}

This function is actually not recursive since it's not calling itself:这个 function 实际上不是递归的,因为它没有调用自己:

else return a*(b,a);

All it's doing is returning a*a .它所做的只是返回a*a It should be:它应该是:

else return a*power(a,b-1);

暂无
暂无

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

相关问题 如何确保密码的长度没有限制? - How can I make sure that there is no limit to how long a password can be? 如何确保我的 char 不是负数 - How can I make sure that my char is not a negative number 如何确保输入适合我的数据类型? - How can I make sure the input suits my data types? 在本机节点模块中,如何确保异步代码始终在同一线程上运行? - In a native node module, how can I make sure that my async code is always running on the same thread? 如何确保我的输入字符串只有字符且不超过 10 个字母? - How can I make sure my input string has only characters & is 10 letters or less? 如何在 C 编程中跟踪递归? - How can I trace recursion in C programming? 如何确保 strtol() 已成功返回? - How do I make sure that strtol() have returned successfully? 我正在尝试在 C 中制作一个程序,您可以在其中玩刽子手,但一旦打印出猜测字母的选项,程序就会终止 - I'm trying to make a program in C in which you can play hangman but as soon as it prints the option to guess the letter the program terminates 如何确保 C 代码(Visual Studio 2013 express + WDK 8.1、WDM kernel 驱动程序)中没有浮点运算? - How can I make sure there is no floating point arithmetic in a C code (Visual Studio 2013 express + WDK 8.1, WDM kernel driver)? 有人可以解释我如何将 for 循环转换为递归 - Can someone explain how can i transform for loop to recursion
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM