C++ 如果数字是整数,如何签入此代码?
我写这段代码是为了检查我在视频中学习到的异常,现在我尝试将立方体做成一个整数,如果输入的数字不是整数,我希望向用户宣布异常C++ 如果数字是整数,如何签入此代码?,c++,int,codeblocks,C++,Int,Codeblocks,我写这段代码是为了检查我在视频中学习到的异常,现在我尝试将立方体做成一个整数,如果输入的数字不是整数,我希望向用户宣布异常 #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
#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;
}
将以下内容添加到源代码中:
#include <math.h> /* round, floor, ceil, trunc */
...
if (x == round(x)) {
...
}
可以在这里找到解释:您可以使用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类型来处理数字。将用户的值作为字符串读取。在调用多维数据集或尝试从中提取数值之前,请检查该字符串是否包含“.”。如果“.”后跟任何数字,则该值不是整数。您还可以丢弃垃圾输入,例如AC$。顺便说一句:整数的拼写只有一个“r”。读取多维数据集函数内的输入是错误的。