你如何在c中使用浮点数作为指数
How can you use a floating point number as an exponent in c
我是运行这段简单的c代码
#include "stdafx.h"
#include "math.h"
int main()
{
float i = 5.5;
float score = 0;
score=i/(i+(2^i));
}
编辑说我是浮点数 "must be an integral or unscoped enum value",我必须保持浮点数。我如何在 c 中使用浮点数作为指数?
改变这个:
score=i/(i+(2^i));
对此:
score = i / (i + pow(2, i));
^
是异或运算符,需要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;
}
输出:
gsamaras@gsamaras-A15:~$ gcc -Wall main.c -lm -o main
gsamaras@gsamaras-A15:~$ ./main
0.108364
截至 c99, as njuffa mentioned, you can use exp2(float n):
Computes 2 raised to the given power n.
而不是:
pow(2, i)
使用:
exp2f(i)
C 中的表达式
2^i
使用按位异或运算符^
,这不是指数,因此建议i
必须是整数类型。
尝试使用数学函数 pow
例如 with
score = i / (i + pow(2,i));
我是运行这段简单的c代码
#include "stdafx.h"
#include "math.h"
int main()
{
float i = 5.5;
float score = 0;
score=i/(i+(2^i));
}
编辑说我是浮点数 "must be an integral or unscoped enum value",我必须保持浮点数。我如何在 c 中使用浮点数作为指数?
改变这个:
score=i/(i+(2^i));
对此:
score = i / (i + pow(2, i));
^
是异或运算符,需要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;
}
输出:
gsamaras@gsamaras-A15:~$ gcc -Wall main.c -lm -o main
gsamaras@gsamaras-A15:~$ ./main
0.108364
截至 c99, as njuffa mentioned, you can use exp2(float n):
Computes 2 raised to the given power n.
而不是:
pow(2, i)
使用:
exp2f(i)
C 中的表达式
2^i
使用按位异或运算符^
,这不是指数,因此建议i
必须是整数类型。
尝试使用数学函数 pow
例如 with
score = i / (i + pow(2,i));