c++ - 为什么主函数无法识别另一个函数是否返回 float 类型的数字

标签 c++

我给 2 和 -2 作为输入,假设得到 0.25 作为输出。但我得到的结果是 1。

#include<iostream>
using namespace std;
float power(float x, float y);

int main()
{
    float x=0, y=0;
    cin>>x>>y;
    cout<<power(x, y)<<endl;
    return 0;
}

float power(float x, float y)
{
    float c;
    if (y == 0) return 1;
    c=x*power(x, (y+1));
    return (1/c);
}

如果我return c;而不是 return 1/c;在主函数中输入 cout<<1/power(x, y);我得到了正确的结果。任何人都可以提出这背后的原因,这对我有帮助。提前谢谢你。

最佳答案

你得到错误结果的原因是在你的递归调用中,你不断地反转结果:

float power(float x, float y) {
    float c;
    cout << y << endl;
    if (y == 0) return 1;
    c=x*power(x, (y+1)); //result previous call (can already been inversed)
    return (1/c); //the inversion step
}

这样发生的是:

pow(2,-2)
    pow(2,-1)
        pow(2,0) = 1
        return 1/(2*1)=0.5
    return 1/(2*0.5)=1 (here you undo the effect)

我省略了两者之间的计算,因为这些计算与显示错误无关。或者更高级的示例:

pow(2,-4)
    pow(2,-3)
        pow(2,-2)
            pow(2,-1)
                pow(2,0) = 1
                return 1/(2*1)=0.5
            return 1/(2*0.5)=1 (here you undo the effect)
        return 1/(2*1)=0.5
    return 1/(2*0.5)=1 (here you undo the effect)

因此您乘以 x 并除以 x。如果原来的 y 是偶数,它总是得到 1.00,否则它会得到 1/x。此外,如果您提供正指数,此方法将永远不会结束。

如果你不不断反转,它会(在负 y 的情况下),简单地计算 x^-y,所以你可以进行反转通话后。

但是您的方法通常很容易出错:众所周知,对 float 执行递增/递减以及检查零会带来麻烦。此外,您的算法效率不高。解决此问题的更好方法(具有整体能力)是:

float power(float x, int y) {
    if(y < 0) {
        return 1.0f/power_positive(x,-y);
    } else {
        return power_positive(x,y);
    }
}
float power_positive(float x, int y) {
    if(y == 0) {
        return 1.0f;
    }
    float r = power_positive(x*x,y>>0x01);
    if(y&0x01) {
        r *= x;
    }
    return r;
}

该算法的运行速度也会更快,因为它每次都将指数除以一半。如前所述,它仅适用于整数指数。你可以概括它。但无论如何,我更相信 80x87 协处理器的浮点运算。

关于c++ - 为什么主函数无法识别另一个函数是否返回 float 类型的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30158164/

相关文章:

c++ - 访问冲突是什么意思?

c++ - 为什么使用字符串初始化的 C++ 位集会被反转?

c++ - 迭代器,循环导致段错误!为什么循环太多了?

c++ Unicode 字符串与易混淆字符的比较。例如(U 0054)应该是==(U03A4)等

c++ - 比较 vector 中的元素并返回对象的最佳方法

c++ - 在 Visual Studio 2010 中测量 C++ 项目性能的问题

c++ - 如何在 C++ 中过滤掉未触及的代码

c++ - 哪个模式在矩阵中出现最多-R(更新)

c++ - VS2010 中的堆错误

c++ - 对象数组的选择排序