Testing if given number is integer(测试给定的数字是否为整数)
问题描述
我正在尝试实现用户定义的函数来测试数字是否为整数:
I am trying to implement user defined function which tests if a number is an integer:
#include <iostream>
#include <typeinfo>
using namespace std;
bool   integer(float k){
                  if (k==20000) return false;;
                  if (k==(-20000)) return  false;
 if (k==0)  return true;
   if (k<0)  return integer(k+1);
   else if(k>0)  return integer (k-1);
   return false;
}
int main(){
    float s=23.34;
       float s1=45;
       cout<<boolalpha;
       cout<<integer(s)<<endl;
       cout<<integer(s1)<<endl;
       return 0;
}
所以这个想法是,如果一个数字是一个整数,不管它是负数还是正数,如果我们将它减一或加一,我们必须得到零,但问题是,我们怎么能为增加和减少创建上限和下限?
So the idea is that,if a number is an integer, does not matter if it is a negative or positive , if we decrease or increase it by one, we must get zero, but the problem is, that how can we create upper and lower bounds for increasing and decreasing?
推荐答案
#include <cmath>
bool is_integer(float k)
{
  return std::floor(k) == k;
}
此解决方案应该适用于 k 的所有可能值.我很确定这是您可以使用 == 安全地比较浮点数的情况.
This solution should work for all possible values of k. I am pretty sure this is a case where you can safely compare floats using ==.
尝试仔细命名函数.integer 并没有给出任何线索它实际上是什么,所以我把函数名改成了更有意义的名字.
Try to thoughtfully name functions. integer does not give any clue what it actually does, so I changed the function name to something more meaningful.
对于未来,测试一个数字是否为整数应该感觉就像一个非常简单的操作,所以你应该有一种强烈的感觉,最好的解决方案将非常简单.我希望你意识到你原来的解决方案是荒谬的,原因有很多(最大的原因:它会在绝大多数情况下导致堆栈溢出).
For the future, testing if a number is integer should feel like a very simple operation, so you should have a strong feeling that the best solution will be very simple. I hope you realize your original solution is absurd for many reasons (biggest reason: it will cause a stack overflow for the vast majority of cases).
这篇关于测试给定的数字是否为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:测试给定的数字是否为整数
 
				
         
 
            
        - 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 从python回调到c++的选项 2022-11-16
- 静态初始化顺序失败 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 近似搜索的工作原理 2021-01-01
- C++ 协变模板 2021-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
 
						 
						 
						 
						 
						 
				 
				 
				 
				