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).
这篇关于测试给定的数字是否为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:测试给定的数字是否为整数
				
        
 
            
        基础教程推荐
- 常量变量在标题中不起作用 2021-01-01
 - C++结构和函数声明。为什么它不能编译? 2022-11-07
 - 如何检查GTK+3.0中的小部件类型? 2022-11-30
 - 在 C++ 中计算滚动/移动平均值 2021-01-01
 - 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
 - 如何通过C程序打开命令提示符Cmd 2022-12-09
 - 我有静态或动态 boost 库吗? 2021-01-01
 - 如何在 C++ 中初始化静态常量成员? 2022-01-01
 - 这个宏可以转换成函数吗? 2022-01-01
 - 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
 
    	
    	
    	
    	
    	
    	
    	
    	
						
						
						
						
						
				
				
				
				