命名空间
变体
操作

fegetround, fesetround

来自 cppreference.cn
< c‎ | numeric‎ | fenv
定义于头文件 <fenv.h>
int fesetround( int round );
(1) (since C99)
int fegetround();
(2) (since C99)

1) 尝试将浮点舍入方向设置为等于参数 round,该参数应为 浮点舍入宏之一。

2) 返回与当前舍入方向相对应的 浮点舍入宏的值。

目录

[编辑] 参数

round - 舍入方向,为 浮点舍入宏之一

[编辑] 返回值

1) 0 成功时返回 0,否则返回非零值。

2) 描述当前舍入方向的 浮点舍入宏,如果无法确定方向,则返回负值。

[编辑] 注释

当前舍入模式,反映最近一次 fesetround 的效果,也可以使用 FLT_ROUNDS 查询。

[编辑] 示例

#include <fenv.h>
#include <math.h>
#include <stdio.h>
 
// #pragma STDC FENV_ACCESS ON
 
void show_fe_current_rounding_direction(void)
{
    printf("current rounding direction:  ");
    switch (fegetround())
    {
           case FE_TONEAREST:  printf ("FE_TONEAREST");  break;
           case FE_DOWNWARD:   printf ("FE_DOWNWARD");   break;
           case FE_UPWARD:     printf ("FE_UPWARD");     break;
           case FE_TOWARDZERO: printf ("FE_TOWARDZERO"); break;
           default:            printf ("unknown");
    };
    printf("\n");
}
 
int main(void)
{
    /* Default rounding direction */
    show_fe_current_rounding_direction();
    printf("+11.5 -> %+4.1f\n", rint(+11.5)); /* midway between two integers */
    printf("+12.5 -> %+4.1f\n", rint(+12.5)); /* midway between two integers */
 
    /* Save current rounding direction. */
    int curr_direction = fegetround();
 
    /* Temporarily change current rounding direction. */
    fesetround(FE_DOWNWARD);
    show_fe_current_rounding_direction();
    printf("+11.5 -> %+4.1f\n", rint(+11.5));
    printf("+12.5 -> %+4.1f\n", rint(+12.5));
 
    /* Restore default rounding direction. */
    fesetround(curr_direction);
    show_fe_current_rounding_direction();
 
    return 0;
}

可能的输出

current rounding direction:  FE_TONEAREST
+11.5 -> +12.0
+12.5 -> +12.0
current rounding direction:  FE_DOWNWARD
+11.5 -> +11.0
+12.5 -> +12.0
current rounding direction:  FE_TONEAREST

[编辑] 参考

  • C23 标准 (ISO/IEC 9899:2024)
  • 7.6.3.1 fegetround 函数 (页码: 待定)
  • 7.6.3.2 fesetround 函数 (页码: 待定)
  • C17 标准 (ISO/IEC 9899:2018)
  • 7.6.3.1 fegetround 函数 (页码: 待定)
  • 7.6.3.2 fesetround 函数 (页码: 待定)
  • C11 标准 (ISO/IEC 9899:2011)
  • 7.6.3.1 fegetround 函数 (页码: 212)
  • 7.6.3.2 fesetround 函数 (页码: 212-213)
  • C99 标准 (ISO/IEC 9899:1999)
  • 7.6.3.1 fegetround 函数 (页码: 193)
  • 7.6.3.2 fesetround 函数 (页码: 193-194)

[编辑] 参见

使用当前舍入模式舍入到整数
(function) [编辑]
(C99)(C99)(C99)(C99)(C99)(C99)(C99)(C99)(C99)
使用当前舍入模式舍入到整数,但
如果结果不同则抛出异常
(function) [编辑]
C++ 文档 for fegetround, fesetround