题目说明:
示例代码:
// Day17_MoreExceptions.cpp: 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <windows.h>
#include <string>
#include <iostream>
using namespace std;
class Calculator
{
public:
int power( int a, int b )
{
int tmp = a;
if( a < 0 || b < 0 )
{
throw runtime_error( "n and p should be non-negative" );
}
else if( a == 0 )
{
return 0;
}
else if( b == 0 )
{
return 1;
}
else
{
while( b-- > 1 )
{
a = a * tmp;
}
}
return a;
}
};
//by zhaocl
int main()
{
Calculator mc = Calculator();
int T, n, p;
cin >> T;
while( T-- > 0 )
{
if( scanf_s( "%d %d", &n, &p ) == 2 )
{
try
{
int num = mc.power( n, p );
cout << num;
}
catch( exception &e )
{
cout << e.what() << endl;
}
}
}
system( "pause" );
return 0;
}
基础知识点:
runtime_error