📜  C++中的rint(),rintf(),rintl()(1)

📅  最后修改于: 2023-12-03 15:29:53.858000             🧑  作者: Mango

C++中的rint(),rintf(),rintl()

在C++中,有三个方法可以用来计算最接近给定参数的整数。这三个方法是 rint()rintf()rintl()。它们都来自于 <cmath> 库。

rint()

rint() 方法返回最接近参数的整数。如果有两个整数与参数的距离相等,则返回偶数。

#include <iostream>
#include <cmath>

int main() {
  double a = 2.3;
  double b = 2.6;
  double c = -2.3;
  double d = -2.6;

  std::cout << std::rint(a) << std::endl;  // Output: 2
  std::cout << std::rint(b) << std::endl;  // Output: 3
  std::cout << std::rint(c) << std::endl;  // Output: -2
  std::cout << std::rint(d) << std::endl;  // Output: -3

  return 0;
}
rintf()

rintf() 方法与 rint() 方法相似,但接受的参数是浮点数(float 类型)。

#include <iostream>
#include <cmath>

int main() {
  float a = 2.3f;
  float b = 2.6f;
  float c = -2.3f;
  float d = -2.6f;

  std::cout << std::rintf(a) << std::endl;  // Output: 2
  std::cout << std::rintf(b) << std::endl;  // Output: 3
  std::cout << std::rintf(c) << std::endl;  // Output: -2
  std::cout << std::rintf(d) << std::endl;  // Output: -3

  return 0;
}
rintl()

rintl() 方法与 rint() 方法相似,但接受的参数是长浮点数(long double 类型)。

#include <iostream>
#include <cmath>

int main() {
  long double a = 2.3l;
  long double b = 2.6l;
  long double c = -2.3l;
  long double d = -2.6l;

  std::cout << std::rintl(a) << std::endl;  // Output: 2
  std::cout << std::rintl(b) << std::endl;  // Output: 3
  std::cout << std::rintl(c) << std::endl;  // Output: -2
  std::cout << std::rintl(d) << std::endl;  // Output: -3

  return 0;
}

这三个方法都返回 double 类型的值,表示最接近参数的整数。

在使用这些方法时,请注意参数的类型和值的范围。如果参数超出了其类型的表示范围,则行为是未定义的。