相关疑难解决方法(0)

检查浮点是否为整数的最佳方法

[有一些问题,但没有一个答案特别明确,有些问题与当前的C++标准已经过时了].

我的研究表明,这些是用于检查浮点值是否可以转换为整数类型的主要方法T.

  1. if (f >= std::numeric_limits<T>::min() && f <= std::numeric_limits<T>::max() && f == (T)f))

  2. 使用std::fmod以提取剩余时间和测试平等为0.

  3. 使用std::remainder和测试相等为0.

第一个测试假定定义f了一个T实例的强制转换.不是真实std::int64_tfloat,例如.

使用C++ 11,哪一个最好?有没有更好的办法?

c++ floating-point c++11 floating-point-conversion

22
推荐指数
2
解决办法
3699
查看次数

如何制作cin >>不将float转换为整数?

我有以下简单的代码:

#include <iostream>
int main()
{
   int a;
   std::cout << "enter integer a" << std::endl;
   std::cin >> a ;

   if (std::cin.fail())
   {
      std::cin.clear();
      std::cout << "input is not integer, re-enter please" <<std::endl;
      std::cin >>a;
      std::cout << "a inside if is: " << a <<std::endl;
   }
   std::cout << "a is " << a <<std::endl;
   std::cin.get();
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

当我运行上面的代码并输入:时1.5,它输出:a is 1.仅供参考:我使用gcc 4.5.3编译并运行代码.

这意味着如果cin期望一个整数但看到一个浮点数,它将隐式地进行转换.那么这是否意味着当cin看到一个浮点数时,它不处于fail()状态?为什么会这样?是因为C++对>>运算符进行隐式转换吗?

我还尝试了以下代码来判断给定的输入数是否是整数,从这篇文章的想法:测试给定的数字是否为整数:

#include <iostream>
bool …
Run Code Online (Sandbox Code Playgroud)

c++ integer cin

0
推荐指数
1
解决办法
6241
查看次数