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

时间:2013-05-27 04:53:20

标签: c++ logarithm pow

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

给定输入:

N  
where N is an integer. 

返回:

True  if N = 2^x, where x is an integer.

我试过这样做,但它不能按我的意愿工作。

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;{
    }
}

请帮帮我。谢谢。

3 个答案:

答案 0 :(得分:5)

正如What Every Computer Scientist Should Know About Floating-Point Arithmetic所解释的那样,计算机程序中的浮点数假装它们可以表示任何实数,但实际上只有32或64位,因此您将四舍五入到最近的表示。即使看起来很简单的数字,比如0.1,在二进制中也有无穷无尽的表示,因此会得到完善。对cospow这样的浮点数运算的函数,就其性质而言,有时会给你错误的错误。结果只是因为“正确的”#39;结果不是一个可代表的浮点。

有时解决方案很复杂。但是在这种情况下,解决方案非常简单 - 检查两个数字&#39;差异小于epsilon,其中epsilon是一个足够小的数字,可以为您提供所需的准确度。 e.g。

float epsilon = 0.0001;
if(abs(b-a) < epsilon)

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

答案 1 :(得分:0)

如果要使用此值,请将值a,b,c声明为double C = LOG10的(a)/日志10(2.0);

如果你想使用它,则将值a,b,c声明为float C = LOG10的(a)/日志10(2.0F);

我一个接一个地执行了这两个更改的程序。它适用于两者 检查语法和示例here

答案 2 :(得分:0)

我认为代码应该读取(给出问题描述。)你想知道N是否是2的幂?

编辑代码

#include <iostream>

int main()
{
    unsigned int N;
    std::cout << "Input a number ";
    std::cin >> N;
    unsigned int two_to_the_power_of_bit = 0;
    do {
        std::cout << "Working on " <<
          two_to_the_power_of_bit << std::endl;
        if (two_to_the_power_of_bit == N) {
            std::cout << "TRUE" << std::endl;
            return 0;
        }

        if (two_to_the_power_of_bit > N) {
            std::cout << "FALSE" << std::endl;
            return 1;
        }

        if (two_to_the_power_of_bit == 0) {
          two_to_the_power_of_bit = 1;
        } else {
          two_to_the_power_of_bit <<= 1;
        }
    } while(two_to_the_power_of_bit);
}

如果我的问题出错我能澄清一下吗?

Output:
Input a number 3
Working on 0
Working on 1
Working on 2
Working on 4
FALSE
mehoggan@mehoggan-Precision-WorkStation-T5500:~/Devel/test$ ./a.out 
Input a number 4
Working on 0
Working on 1
Working on 2
Working on 4
TRUE
mehoggan@mehoggan-Precision-WorkStation-T5500:~/Devel/test$ ./a.out 5
Input a number 5
Working on 0
Working on 1
Working on 2
Working on 4
Working on 8
FALSE
mehoggan@mehoggan-Precision-WorkStation-T5500:~/Devel/test$