N = 2 ^ x,如果为真,则写入true.为什么这是错的?

Pra*_*aja 0 c++ logarithm pow

请帮我编码.我想做一个像这样的程序.对不起坏英语.

给定输入:

N  
where N is an integer. 
Run Code Online (Sandbox Code Playgroud)

返回:

True  if N = 2^x, where x is an integer.
Run Code Online (Sandbox Code Playgroud)

我试过这样做,但它不能像我想的那样工作.

using namespace std;
int main()
{
    float a,b,c;
    cin>>a;
    c=log10(a)/log10(2.0);
    b=pow(2,c);
    if(b==a)
    {
        cout<<"TRUE"<<endl;}
    else
        cout<<"FALSE"<<endl;{
    }
}
Run Code Online (Sandbox Code Playgroud)

请帮帮我.谢谢.

Pat*_*shu 5

正如每个计算机科学家应该知道的关于浮点运算的解释,计算机程序中的浮点数假装它们可以表示任何实数,但实际上只有32或64位,因此您将四舍五入到最近的表示.即使看起来很简单的数字,比如0.1,在二进制中也有无穷无尽的表示,因此会得到完善.上浮点数操作一样的功能cospow会,根据其性质,有时会给你的"错误"的结果仅仅是因为"正确"的结果不是representible浮点.

有时解决方案很复杂.然而,在这种情况下,解决方案非常简单 - 检查两个数字的差异是否小于epsilon,其中epsilon是一个足够小的数字,可以为您提供所需的准确度.例如

float epsilon = 0.0001;
if(abs(b-a) < epsilon)
Run Code Online (Sandbox Code Playgroud)

此外,每当您需要超过速度和尺寸的精度时,请double优先使用float.它的两倍大,因此许多重要的地方更精确.