如果数字是整数,我如何检查此代码
How do I check in this code if the number is in integer?
我写了这段代码来检查我在视频中学到的异常,现在我尝试制作整数的立方体,如果输入的数字不是整数,我希望向用户宣布异常。
#include <iostream>
float cube( float x)
{
char ch;
std::cin.get(ch);
if(ch=='.')
throw "Should be an integrer";
float cube=x*x*x;
return cube;
}
int main ()
{
float x;
std::cout<<" Enter an integrer : ";
std::cin>>x;
float cube_x=cube(x);
std::cout<<"Cube("<<x<<")="<<cube_x<<std::endl;
return 0;
}
您可以使用 boost 词法转换,这正是为此目的。它将引发转换失败的异常。Boost经过充分测试,您可以使用它为您进行转换。
这可能看起来像这样:
#include <boost/lexical_cast.hpp>
#include <iostream>
int cube(int x)
{
return x*x*x;
}
int main()
{
std::string x;
std::cout << " Enter an integrer : ";
std::cin >> x;
try
{
int y = boost::lexical_cast<int>(x);
int cube_x = cube(y);
std::cout << "Cube(" << x << ")=" << cube_x << std::endl;
}
catch (const boost::bad_lexical_cast &e)
{
std::cerr << e.what() << 'n';
}
return 0;
}
顺便说一下,如果你的程序只处理整数,你也应该使用类型 int
而不是 float
来处理数字。
将以下内容添加到源代码中:
#include <math.h> /* round, floor, ceil, trunc */
...
if (x == round(x)) {
...
}
解释可以在这里找到: C++参考
相关文章:
- 你能检查一下为什么在这个代码中从链接列表中删除项目不起作用吗
- 静态代码检查器抱怨.虚惊一场?
- 编写了一个C++代码来检查表达式是否具有平衡括号并且我的代码未运行.我已经卡了一天了
- R 包中的 TMB c++ 代码和 CRAN 检查
- 我遇到了这个代码片段,不明白. 它递归检查 C++ 字符串中是否存在大写字符
- 使用 gtest 框架在单元测试代码中检查目标对象的私有变量的最佳实践是什么?
- 我的重复检查代码中的错误究竟在哪里?
- 有没有办法在c ++中清除空数组,请检查下面的代码以获取说明
- 避免使用 std::any 编写相同的重复类型检查代码
- C++:此代码可以编译,但引发运行时检查失败 #2 - 围绕变量周围的堆栈'num'已损坏。发生
- 如何检查 win32 exe 文件是否已运行?(使用 win32 API 代码)
- C++ 二次方程对于代码检查器无法正常工作
- 通过SWIG禁用python-c 接口的隐式类型检查代码
- cMake/cTest:检查代码是否编译
- 是否有宏或规定要检查代码行是否在类内
- 是否可以在测试后检查代码覆盖率是否增加
- 检查代码是否在GPU或CPU上运行
- c++ 11类型检查代码的奇怪编译警告
- 什么调试器可以检查c++代码是否存在内存泄漏
- 如何在运行时检查代码是否由给定的asio::strand实例保护