【问题标题】:How can you use a floating point number as an exponent in c [duplicate]如何在c中使用浮点数作为指数[重复]
【发布时间】:2016-10-01 15:31:12
【问题描述】:

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

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

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

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

}

并且编辑器说浮动 i“必须是一个整数或无范围的枚举值”,并且 i 保持浮动是必不可少的。如何在 c 中使用浮点数作为指数?

【问题讨论】:

  • ^ 不是 C 中的幂运算!在做出任何不确定的假设之前,请阅读有关 C 的教程!

标签: c function math floating-point exponent


【解决方案1】:

改变这个:

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

截至,正如njuffa所说,您可以使用exp2(float n)

计算 2 的给定幂 n。

而不是:

pow(2, i)

使用:

exp2f(i)

【讨论】:

  • 成功了,谢谢!
  • 太棒了@J.doo,别忘了接受一个答案!
  • 在性能和准确性方面,这里使用exp2f(i) 可能比pow(2,i) 更好,并且可以说更清晰。
  • @njuffa 我不知道那个功能。但是,我不得不承认,我必须真正阅读 ref (!) 才能了解 i 的作用(但由于您的评论,我已经知道很多了)! ;)
【解决方案2】:

C 中的表达式

2^i

使用按位异或运算符^,这不是指数,因此建议i 必须是整数类型。

尝试使用数学函数pow,例如with

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

【讨论】:

    猜你喜欢
    • 2017-03-22
    • 1970-01-01
    • 1970-01-01
    • 2013-09-13
    • 1970-01-01
    • 1970-01-01
    • 2015-02-17
    • 2013-03-10
    • 2012-10-27
    相关资源
    最近更新 更多