小弟想求2的N次方,但是求出来不对头,请大家帮我看看,谢谢!!
偶在程序中这样写了几句:
....
#include <math.h>
.......
.......
int n = 4;                 //求2的4次方
printf("%d\n" , pow(2,n)); //该式结果为0
printf("%d\n" , 2^n);      //该式结果为6
.......
......
上面结果不知道是怎么回事啊????虽然我后来能这样求:printf("%d" , 2<<(p-1));
但是我先前的两种方法为什么不行呢?不甘心啊!
请大家看看吧,谢谢!!!

解决方案 »

  1.   


    2^6表示 2与4疑惑,010 ^ 100 的结果是 110嘛,
    ^在BASIC里面是乘方的运算符,这里不是。
      

  2.   

    用C的,看不大懂(POW(INT,INT)是本来有的???)
    C++里可以这样
    #include<iostream.h>
    #include<math.h>
    const int m=2;      //全局
    int pow(int m,int n)
    {
    if(n=0)
    return 1;
    else
    return 2*pow(m,n-1);//递归
    }
    void main()
    {
    int n=4;
    cout<<pow(m,n)<<endl;
    }
    C的也差不多吧
      

  3.   

    至于printf("%d\n" , pow(2,n)); //该式结果为0因为pow函数返回的是double类型的量,但是你用%d试图打印它,
    而打印出来0,。
    你可以强制转换一下。printf("%d\n" , (int)pow(2,n));
      

  4.   

    2的n次方,一个速度很快,语句很少的方法:
    int Pow(int n)  //2 的n次方函数,结果在返回值中
    {
        return (1 << n);
    }
      

  5.   

    自已定义一个递归调用....float fun(int n)
    {
    int k =n;
    float result =1;
    while(k)
    {
     result = result*n;
     k--;
    }
    retrun result;}
      

  6.   

    float fun(int tmp ,int n)
    {
    int k =n;
    float result =1;
    while(k)
    {
     result = result*tmp;
     k--;
    }
    retrun result;}