使用递归的

时间:2017-01-28 18:13:58

标签: c++ recursion

我使用以下算法将分数转换为其十六进制等效值:

.142857 * 16 = 2.285712
.285712 * 16 =  4.571429

我继续乘以剩余部分,直到它等于原始余数或零。

所以我编写了这个函数来尝试递归地执行这个算法:

int * getHex(int * arr, double original, double result, int index) {
    double newResult, fraction, integer;
    newResult = result;
    fraction = modf(newResult, &integer);
    cout << "fraction " << fraction << " the result " << rem << endl;
    arr[index] = (int)integer;
    if(fraction == original) cout << "test" << endl;
    if (fraction == 0 || fraction == original) {
       return arr;
    }
    index += 1;
    return resultToHex(hexArr, result, fraction * 16, index);
}

我这样称呼这个方法:

int * arr = new int[100];
int num = stoi(numerator, nullptr, 16);
int den = stoi(denominator, nullptr, 16);
double rem = 1 + ( (double)(num - den) / den);
double result = rem * 16;

arr = getHex(arr, rem, result, 0);

问题在于,fraction永远不等于传递rem,即使在我cout时我发现fraction肯定等于rem 。我正在谈论的一个例子:

当分子为1且分母为7时:

rem = .142857
result = 2.28571

然后我调用该函数,将上面的参数作为参数传递:

getHex(arr, rem, result, 0);

这是coutgetHex的结果:

 the fraction 0.285714 result 0.142857
 the fraction 0.571429 result 0.142857
 the fraction 0.142857 result 0.142857 // the fraction equals the original remainder
 the fraction 0.285714 result 0.142857
 the fraction 0.571429 result 0.142857
 the fraction 0.142857 result 0.142857
 the fraction 0.285714 result 0.142857
 the fraction 0.571429 result 0.142857
 the fraction 0.14286 result 0.142857
 the fraction 0.285767 result 0.142857
 the fraction 0.572266 result 0.142857
 the fraction 0.15625 result 0.142857
 the fraction 0.5 result 0.142857
 the fraction 0 result 0.142857

我无法弄清楚为什么我的函数继续执行,即使在第三次迭代后,分数等于余数。我找不到这个bug。我在这里错过了什么?

1 个答案:

答案 0 :(得分:1)

if(fraction == original)&lt; ==您正在比较双重值是否相等。

你永远不应该这样做。

它永远不会奏效。

为什么比较double或float值的相等性不起作用,有很多帖子。

例如:How dangerous is it to compare floating point values?

相关问题