Namespaces
Variants

round, roundf, roundl, lround, lroundf, lroundl, llround, llroundf, llroundl

From cppreference.net
< c ‎ | numeric ‎ | math
Common mathematical functions
Functions
Basic operations
(C99)
(C99)
(C99)
(C99) (C99) (C99) (C23)
Maximum/minimum operations
Exponential functions
Power functions
Trigonometric and hyperbolic functions
Nearest integer floating-point
round lround llround
(C99) (C99) (C99)
(C99)

(C99) (C99) (C99)
(C23) (C23) (C23) (C23)
Floating-point manipulation
Narrowing operations
(C23)
(C23)
(C23)
(C23)
(C23)
(C23)
Quantum and quantum exponent
Decimal re-encoding functions
Total order and payload functions
Classification
Error and gamma functions
(C99)
(C99)
(C99)
(C99)
Types
Macro constants
Special floating-point values
Arguments and return values
Error handling
Fast operation indicators
Definido en el encabezado <math.h>
float roundf ( float arg ) ;
(1) (desde C99)
double round ( double arg ) ;
(2) (desde C99)
long double roundl ( long double arg ) ;
(3) (desde C99)
Definido en el encabezado <tgmath.h>
#define round( arg )
(4) (desde C99)
Definido en el encabezado <math.h>
long lroundf ( float arg ) ;
(5) (desde C99)
long lround ( double arg ) ;
(6) (desde C99)
long lroundl ( long double arg ) ;
(7) (desde C99)
Definido en el encabezado <tgmath.h>
#define lround( arg )
(8) (desde C99)
Definido en el encabezado <math.h>
long long llroundf ( float arg ) ;
(9) (desde C99)
long long llround ( double arg ) ;
(10) (desde C99)
long long llroundl ( long double arg ) ;
(11) (desde C99)
Definido en el encabezado <tgmath.h>
#define llround( arg )
(12) (desde C99)
1-3) Calcula el valor entero más cercano a arg (en formato de coma flotante), redondeando los casos intermedios alejándose de cero, independientemente del modo de redondeo actual.
5-7, 9-11) Calcula el valor entero más cercano a arg (en formato entero), redondeando los casos intermedios alejándose de cero, independientemente del modo de redondeo actual.
4,8,12) Macros genéricas de tipos: Si arg tiene tipo long double , roundl , lroundl , llroundl se llama. De lo contrario, si arg tiene tipo entero o el tipo double , round , lround , llround se llama. De lo contrario, roundf , lroundf , llroundf se llama, respectivamente.

Contenidos

Parámetros

arg - valor de punto flotante

Valor de retorno

Si no ocurren errores, se devuelve el valor entero más cercano a arg , redondeando los casos intermedios alejándose de cero.

Valor de retorno
math-round away zero.svg
Argumento

Si ocurre un error de dominio, se devuelve un valor definido por la implementación.

Manejo de errores

Los errores se reportan como se especifica en math_errhandling .

Si el resultado de lround o llround está fuera del rango representable por el tipo de retorno, puede ocurrir un error de dominio o un error de rango.

Si la implementación soporta aritmética de punto flotante IEEE (IEC 60559):

Para las funciones round , roundf , y roundl :
  • El modo de redondeo actual no tiene efecto .
  • Si arg es ±∞, se devuelve sin modificaciones.
  • Si arg es ±0, se devuelve sin modificaciones.
  • Si arg es NaN, se devuelve NaN.
Para las familias de funciones lround y llround :
  • FE_INEXACT nunca se activa.
  • El modo de redondeo actual no tiene efecto .
  • Si arg es ±∞, se activa FE_INVALID y se devuelve un valor definido por la implementación.
  • Si el resultado del redondeo está fuera del rango del tipo de retorno, se activa FE_INVALID y se devuelve un valor definido por la implementación.
  • Si arg es NaN, se activa FE_INVALID y se devuelve un valor definido por la implementación.

Notas

FE_INEXACT puede (pero no está obligada a) ser activada por round al redondear un valor finito no entero.

Los valores de punto flotante más grandes representables son enteros exactos en todos los formatos estándar de punto flotante, por lo que round nunca desborda por sí mismo; sin embargo, el resultado puede desbordar cualquier tipo entero (incluyendo intmax_t ), cuando se almacena en una variable entera.

POSIX especifica que todos los casos donde lround o llround generan FE_INVALID son errores de dominio.

La versión double de round se comporta como si estuviera implementada de la siguiente manera:

#include <math.h>
#pragma STDC FENV_ACCESS ON
double round(double x)
{
    return signbit(x) ? ceil(x - 0.5) : floor(x + 0.5);
}

Ejemplo

#include <assert.h>
#include <fenv.h>
#include <float.h>
#include <limits.h>
#include <math.h>
#include <stdio.h>
// #pragma STDC FENV_ACCESS ON
double custom_round(double x)
{
    return signbit(x) ? ceil(x - 0.5) : floor(x + 0.5);
}
void test_custom_round()
{
    const double sample[] =
    {
        0.0, 2.3, 2.5 - DBL_EPSILON, 2.5, 2.5 + DBL_EPSILON, 2.7, INFINITY
    };
    for (size_t t = 0; t < sizeof sample / sizeof(double); ++t)
        assert(round(+sample[t]) == custom_round(+sample[t]) &&
               round(-sample[t]) == custom_round(-sample[t]));
}
int main(void)
{
    // round
    printf("round(+2.3) = %+.1f  ", round(2.3));
    printf("round(+2.5) = %+.1f  ", round(2.5));
    printf("round(+2.7) = %+.1f\n", round(2.7));
    printf("round(-2.3) = %+.1f  ", round(-2.3));
    printf("round(-2.5) = %+.1f  ", round(-2.5));
    printf("round(-2.7) = %+.1f\n", round(-2.7));
    printf("round(-0.0) = %+.1f\n", round(-0.0));
    printf("round(-Inf) = %+f\n",   round(-INFINITY));
    test_custom_round();
    // lround
    printf("lround(+2.3) = %+ld  ", lround(2.3));
    printf("lround(+2.5) = %+ld  ", lround(2.5));
    printf("lround(+2.7) = %+ld\n", lround(2.7));
    printf("lround(-2.3) = %+ld  ", lround(-2.3));
    printf("lround(-2.5) = %+ld  ", lround(-2.5));
    printf("lround(-2.7) = %+ld\n", lround(-2.7));
    printf("lround(-0.0) = %+ld\n", lround(-0.0));
    printf("lround(-Inf) = %+ld\n", lround(-INFINITY)); // FE_INVALID raised
    // error handling
    feclearexcept(FE_ALL_EXCEPT);
    printf("lround(LONG_MAX+1.5) = %ld\n", lround(LONG_MAX + 1.5));
    if (fetestexcept(FE_INVALID))
        puts("    FE_INVALID was raised");
}

Salida posible:

round(+2.3) = +2.0  round(+2.5) = +3.0  round(+2.7) = +3.0
round(-2.3) = -2.0  round(-2.5) = -3.0  round(-2.7) = -3.0
round(-0.0) = -0.0
round(-Inf) = -inf
lround(+2.3) = +2  lround(+2.5) = +3  lround(+2.7) = +3
lround(-2.3) = -2  lround(-2.5) = -3  lround(-2.7) = -3
lround(-0.0) = +0
lround(-Inf) = -9223372036854775808
lround(LONG_MAX+1.5) = -9223372036854775808
    FE_INVALID was raised

Referencias

  • Estándar C23 (ISO/IEC 9899:2024):
  • 7.12.9.6 Las funciones round (p: TBD)
  • 7.12.9.7 Las funciones lround y llround (p: TBD)
  • 7.25 Matemáticas genéricas de tipos <tgmath.h> (p: TBD)
  • F.10.6.6 Las funciones round (p: TBD)
  • F.10.6.7 Las funciones lround y llround (p: TBD)
  • Estándar C17 (ISO/IEC 9899:2018):
  • 7.12.9.6 Las funciones round (p: 184)
  • 7.12.9.7 Las funciones lround y llround (p: 184-185)
  • 7.25 Matemáticas genéricas de tipos <tgmath.h> (p: 272-273)
  • F.10.6.6 Las funciones round (p: 384)
  • F.10.6.7 Las funciones lround y llround (p: 385)
  • Estándar C11 (ISO/IEC 9899:2011):
  • 7.12.9.6 Las funciones round (p: 253)
  • 7.12.9.7 Las funciones lround y llround (p: 253)
  • 7.25 Matemáticas genéricas de tipos <tgmath.h> (p: 373-375)
  • F.10.6.6 Las funciones round (p: 527)
  • F.10.6.7 Las funciones lround y llround (p: 528)
  • Estándar C99 (ISO/IEC 9899:1999):
  • 7.12.9.6 Las funciones round (p: 233)
  • 7.12.9.7 Las funciones lround y llround (p: 234)
  • 7.22 Matemáticas genéricas de tipo <tgmath.h> (p: 335-337)
  • F.9.6.6 Las funciones round (p: 464)
  • F.9.6.7 Las funciones lround y llround (p: 464)

Véase también

calcula el entero más grande no mayor que el valor dado
(función)
(C99) (C99)
calcula el entero más pequeño no menor que el valor dado
(función)
(C99) (C99) (C99)
redondea al entero más cercano no mayor en magnitud que el valor dado
(función)