本乘方算法,只能计算整数long范围内乘方,主要是练习信号处理
#include<iostream>
#include<stdexcept>
using std::cin;
using std::cout;
using std::endl;
long pows(long base,long time);
int main()
{
long t1,t2;
for (;;)
{
try
{
cout<<"Please input the base number and how many times it is multiplied?"<<endl
<<"example:8 13."<<endl;
cin.clear();
cin.sync();
cin>>t1>>t2;
if (cin) cout<<pows(t1,t2)<<endl;
else throw std::invalid_argument("Not a suitable input");
}
catch (std::invalid_argument err_ar)
{
cout<<err_ar.what()<<endl<<"Continue??"<<endl<<"Input 'n' to exit"<<endl
<<"Input anything else to continue inputing."<<endl;
cin.clear();
cin.sync();
char tmp_test;
cin>>tmp_test;
if (cin&&tmp_test=='n') break;
}
catch (std::range_error err_ra)
{
cout<<err_ra.what()<<endl;
cout<<"Try again"<<endl;
}
catch (std::length_error err_le)
{
cout<<err_le.what()<<endl;
cout<<"Try again"<<endl;
}
}
system("pause");
return 0;
}
long pows(long base,long time)
{
if (time<0)
{
throw std::range_error("Now I can't work it out!!");
}
else
{
if (time==0) return 1;
long max(LONG_MAX/base),sum(base);
for (long i=1; i<time; ++i)
{
if (sum>max)
{
throw std::length_error("Too big a number");
}
else
{
sum*=base;
}
}
return sum;
}
}