简体   繁体   English

具有双输出的递归函数

[英]recursive function with double output

I am trying to make an recursive function. 我试图做一个递归函数。 i will be an integer, however the output will be an double. 我将是一个整数,但是输出将是一个双精度型。 I know the function cannot take an double to start, however when the function reaches it maximum "depth", i will still be an integer. 我知道函数不能花一倍的时间来启动,但是当函数达到最大“深度”时,我仍然是整数。 When it will go "up" the output will become an double, but i do not understand why the function will not work. 当它将“上升”时,输出将变为两倍,但是我不明白为什么该功能将无法正常工作。

long sum1(int i) {
  if(i==1) {
    return 1;
  } else {
    return sum1(i-1) + 1/i;
  }
}

This is my code to perform this serie: 这是我执行此系列的代码:

  1. series1(i) = 1 + 1/2 + 1/3 + . 系列1(i)= 1 + 1/2 + 1/3 +。 . . 1/i 1 / i

The output does not give an error, but the result is not compute correctly. 输出没有给出错误,但是结果计算不正确。

First of all 1/i will always be 0 when i > 1, since you are dividing two int s. 首先,当i > 1时, 1/i将始终为0,因为您将两个int相除。

Second of all, since the return type is long , any fractions will be truncated anyway. 其次,由于返回类型为long ,因此任何分数都将被截断。

You should return a double for an accurate result: 您应该返回一个double精度值以获得准确的结果:

double sum1(int i) {
  if(i==1) {
    return 1.0;
  } else {
    return sum1(i-1) + 1.0/i;
  }
}

Well the problem for the wrong calculation is that sum1(i-1) + 1/i; 那么错误计算的问题是sum1(i-1) + 1/i; results in an integer calculation. 导致整数计算。 And 1/i when i is integer >1 is always = 0. 当i为整数> 1时,1 / i始终为0。

Just use double for the recursion and you can pass int argument. 只需对double使用递归,就可以传递int参数。

double sum1(double i) {
          if(i==1) {
            return 1;
          } else {
            return sum1(i-1) + 1/i;
          }
        }

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

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