编译时的浮点运算 [英] Floating point arithmetic at compile-time

查看:72
本文介绍了编译时的浮点运算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在编译时或运行时是否执行使用编译时常量整数的浮点计算?例如,除法运算是在何时计算的:

Are floating point calculations, which use compile-time constant integers, performed during compile-time or during run-time? For example, when is the division operation calculated in:

template <int A, int B>
inline float fraction()
{
    return static_cast<float>(A) / B;
}

推荐答案

我相信它是实现定义的,但是大多数编译器会在编译时评估常量表达式.但是,即使您没有进行以下修改:

I believe it is implementation defined, but most compilers will evaluate constant expressions at compile time. However even if yours does not the following modification:

template <int A, int B>
inline float fraction()
{
    static const float f = static_cast<float>(A) / B;
    return f ;
}

至少可以确保表达式在运行时被评估一次.

will at least ensure that the expression is evaluated just once if it is evaluated at runtime.

这篇关于编译时的浮点运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆