开发者

Recursive function returns unexpected result

开发者 https://www.devze.com 2023-01-05 01:26 出处:网络
My funciton takes a number input from the user and recursively sums the number \'n\' to one. Inputting a 5 would开发者_开发问答 sum 1/5 + 1/4 + 1/3+ 1/2 + 1/1.

My funciton takes a number input from the user and recursively sums the number 'n' to one.

Inputting a 5 would开发者_开发问答 sum 1/5 + 1/4 + 1/3+ 1/2 + 1/1.

#include<stdio.h>
#include<conio.h>
//to 
float recursion(float num,float sum);
void main(void)
{
  float num=5,sum=0;
  //input num
  printf("%d",recursion(num,sum));

  getch();
}
 
float recursion(float num,float sum)
{
  // int sum=0; every time u run it the sum is assigned 0
  if( num==1)
    return 1;
  else
  {
    sum=sum+(1/num);
    num--;
    recursion(num,sum);
  }
  return sum;
}//recursion function ends

The problem is, that it is giving 0. Can anyone help, please?


You should return the result of the recursive call:

return recursion(num,sum);

instead of return sum.


Why's the printf("%d") while it's supposed to print a float? Doesn't that display an integer making it always 0 for a float less than 0?

float recursion(float num)
{
    if( num==1.0f)
    {
        printf("1/1 = ");
        return 1.0f;
    }
    float inverse = 1.0f/num;
    printf("1/%.0f + ", num);
    return (inverse + recursion(--num));
}//recursion function ends

Here's the test code:

float num=5,sum=0;
float expected = 0;
for (int i = 1; i <= num; ++i)
{
    expected += 1.0f/i;
}
//input num
printf("Expected %f and got %f",expected, recursion(num));

Output:
1/5 + 1/4 + 1/3 + 1/2 + 1/1 = Expected 2.283334 and got 2.283334

Hope this helps.


float recursion(float num) {
  if( num==1) 
    return 1; 
  return (1.0/num) + recursion(num - 1);
}

By the way, do not input a negative number!


@fahad: Changes in your code has been commented in the code below:

float recursion2(float num,float sum)
{
    // int sum=0; every time u run it the sum is assigned 0
    if( num==1)
        // Vite Falcon: Needs to return sum + 1
        return sum + 1.0f;
    else
    {
        // Vite Falcon: This is not really necessary.
        //sum=sum+(1/num);
        float inverse = 1.0f/num;
        num--;
        // Vite Falcon: The new sum is returned by the recursive function and so
        // should be stored and returned.
        sum = recursion2(num,sum + inverse);
    }
    return sum;
}//recursion function ends

PS: Sorry I had to answer again because I don't know how to add multi-line code as a comment.


Use sum=sum+(1.0/num);. When you divide 1, an integer with a float, the float gets converted to integer first.


float recursion(int num) {
  if (num == 0) {
    return 0;
  }

  return 1 / num + recursion(num--);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消