测试给定的数字是否为整数 [英] Testing if given number is integer

查看:23
本文介绍了测试给定的数字是否为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现用户定义的函数来测试数字是否为整数:

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).

这篇关于测试给定的数字是否为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆