【发布时间】:2016-07-16 10:50:31
【问题描述】:
我尝试计算 power(n,p) 并在 n 或 p codechef
中编译时出现 Time Limited Exceeded 错误
问:
1. C++什么时候出现Time Limited Exceeded错误?
2.我的代码哪里错了?
#include <cmath>
#include <iostream>
#include <exception>
#include <stdexcept>
#include <cstdio>
using namespace std;
class Calculator{
public:
int power(int n,int p){
if(n<0 || p < 0)
throw "n and p should be non-negative";
else
return power(n,p);
}
};
int main()
{
Calculator myCalculator=Calculator();
int T,n,p;
cin>>T;
while(T-->0){
if(scanf("%d %d",&n,&p)==2){
try{
int ans=myCalculator.power(n,p);
cout<<ans<<endl;
}
catch(exception& e){
cout<<e.what()<<endl;
}
}
}
}
【问题讨论】:
-
你有没有试过运行你的代码(即使是简单的输入)?我怀疑你没有。
-
该错误不是 C++ 错误,而是来自该网站的错误。阅读他们的帮助材料以准确了解它的含义(但很可能您的程序运行时间太长,他们不允许这样做,并且要修复它,您必须使您的程序完成得更快,或者更有可能修复一个错误)。
-
是的,我尝试按照输入 2 -3 5 2 4
-
我不知道您尝试运行什么示例输入。您应该使用最简单的输入获得无限递归。这就是为什么我怀疑您在此处发布问题之前没有尝试运行和调试。
-
请先付出一些努力。当您返回时,在您的 power() 方法中,您需要调用 pow(n,p)。