does the c preprocessor handle floating point math constants

只谈情不闲聊 提交于 2021-02-19 07:12:44

问题


Say that I have

   #define A 23.9318;
   #define B 0.330043;
   #define C 5.220628;

I want to do

const unsigned result =  (unsigned)(0x01000000 * ( A * B / C ));    // unsigned is 32 bit

What I hope for is to have result with fixed decimal representation of the floating point calculations.

I cannot pre combine A,B,C together as their definition is not part of my code and I need it to work if they are changed.


回答1:


No, the standard C preprocessor operations do not perform floating-point arithmetic.

A C implementation is permitted, but not required, by the C standard to perform these operations at compile-time.




回答2:


This is not being offered as another answer, just an illustration that will not fit into the comments...

In a C99 compiler, with the following code, I get the following results (comments):

#include <ansi_c.h>

#define A 23.9318
#define B 0.330043
#define C 5.220628

#define result A*B/C  //1.512945007267325

const unsigned resultB = (unsigned)result*(0x01000000);

int main(void)
{
    resultB; //24394701

    return 0;
}  

So, although not required, some C implementations do include compile-time computations of floating point.



来源:https://stackoverflow.com/questions/21241031/does-the-c-preprocessor-handle-floating-point-math-constants

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!