2016-10-01 82 views
1

我正在這一段簡單的C代碼你怎麼能在C

#include "stdafx.h" 
#include "math.h" 

int main() 
{ 
float i = 5.5; 
float score = 0; 

score=i/(i+(2^i)); 

} 

使用浮點數作爲指數和編輯說,浮動我「必須是整數或無範圍的枚舉值」 ,而且我仍然是一個漂浮者是至關重要的。我如何使用float作爲c中的指數?

+3

''^是不是在C冪!在做出任何未假設的假設之前閱讀關於C的教程! – fuz

回答

5

更改此:

score=i/(i+(2^i)); 

這樣:

score = i/(i + pow(2, i)); 

^是XOR運算符,你需要pow(double base, double exponent);把一切融合在一起:

#include "math.h" 
#include "stdio.h" 

int main() 
{ 
     float i = 5.5; 
     float score = 0; 

     score = i/(i + pow(2, i)); 
     printf("%f\n", score); 
     return 0; 
} 

輸出:

[email protected]:~$ gcc -Wall main.c -lm -o main 
[email protected]:~$ ./main 
0.108364 

截至,如njuffa提到的,你可以使用exp2(float n)

計算2提升到給定的n次方。並且代替

pow(2, i) 

使用:

exp2f(i) 
+0

這樣做,謝謝! –

+0

很棒@ J.doo,別忘了*接受*一個答案! – gsamaras

+0

在性能和準確性方面,使用'exp2f(i)'而不是'pow(2,i)'可能更好,並且可以更清楚地說明。 – njuffa

1

在C表達

2^i 

使用按位XOR運算符^,這不是一個指數,因此建議i必須是整數類型。

嘗試使用數學函數pow如用

score = i/(i + pow(2,i));