测试如果给定的数字是整数 [英] testing if given number is integer

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

问题描述

我试图实现测试数字是否为整数的用户定义函数

i am trying to implement user defined function which tests if number is 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;

}

所以想法是,如果number是整数,如果我们减少或增加一个,我们必须得到零,但问题是,如何创建上下限增加和减少?

so idea is that,if number is integer, does not matter it is negative or positive ,if we decrease or increase by one, we must get zero,but problem is, that how can create upper and lower bound for increasing and decreasing?

推荐答案

#include <cmath>

bool is_integer(float k)
{
  return std::floor(k) == k;
}

此解决方案应适用于所有可能的值 k 。我很确定这是一个case你可以安全地比较浮动使用 ==

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天全站免登陆