测试如果给定的数字是整数

编程入门 行业动态 更新时间:2024-10-23 21:39:21
本文介绍了测试如果给定的数字是整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

更多推荐

测试如果给定的数字是整数

本文发布于:2023-10-25 14:10:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1527188.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:整数   数字   测试

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!