如何在c中使用浮点数作为指数

1 c math floating-point function exponent

我正在运行这个简单的c代码

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

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

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

}
Run Code Online (Sandbox Code Playgroud)

并且编辑说浮动我"必须是一个整数或未整合的枚举值",并且我必须保持浮动.如何在c中使用float作为指数?

gsa*_*ras 5

改变这个:

score=i/(i+(2^i));
Run Code Online (Sandbox Code Playgroud)

对此:

score = i / (i + pow(2, i));
Run Code Online (Sandbox Code Playgroud)

^是XOR运算符,你需要pow(双基,双指数) ; 将所有东西放在一

#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;
}
Run Code Online (Sandbox Code Playgroud)

输出:

gsamaras@gsamaras-A15:~$ gcc -Wall main.c -lm -o main
gsamaras@gsamaras-A15:~$ ./main 
0.108364
Run Code Online (Sandbox Code Playgroud)

,正如njuffa所提到的,你可以使用exp2(float n):

计算2提升到给定的功率n.

而不是:

pow(2, i)
Run Code Online (Sandbox Code Playgroud)

使用:

exp2f(i)
Run Code Online (Sandbox Code Playgroud)