时间限制超出错误C++编译
Time Limited Exceeded error C++ compile
如果n或p<0作为以下代码。但在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;
}
}
}
}
之所以会发生这种情况,是因为代码中有无限递归。
看看这篇文章:
int power(int n,int p){
if(n<0 || p < 0)
throw "n and p should be non-negative";
else
return power(n,p);
}
它将无限次调用power(n, p)
,因为您没有退出执行的条件。所以你只需要把一个又一个函数调用放在堆栈上。你甚至不做任何计算!
你需要这样的退出条件:
int power(int n,int p){
if(n<0 || p < 0)
throw "n and p should be non-negative";
else if (p == 0)
{
return 1;
}
return n*power(n,p-1);
}
Calculator::power
是无限递归的:它使用与接收到的参数相同的参数调用自己。肯定应该有乘法在那里某处…;-]
超过时间限制是一个错误,当在一定时间后没有生成输出时,在您的情况下,您有一个称为幂(a,b)的无限递归如果a>0&;b>0,然后调用幂(a,b),从而进入无限递归尝试添加此
int power(int n, int p){ if(n<0 || p < 0) throw "n and p should be non-negative";
else if (p == 1) return 1;
else return n*(n,p-1);}
您的代码几乎是正确的。只是一个小案子处理不当。在计算一个数字的幂时,您已经用相同的参数再次递归调用了相同的函数。这里没有提供基本情况,因此您的函数不知道何时停止。你可以做一些这样的改变:
在函数中使用基本情况:如果(p==0)返回1;
并用欺骗的力量递归调用您的函数:return(n*(幂(n,p-1));
你的问题很容易解决。
相关文章:
- 警告处理为错误这里有什么问题
- "error: no matching function for call to"构造函数错误
- boost::进程间消息队列引发错误
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- QT在错误的班级中寻找空位
- vector.resize()中的分配错误
- 代码在main()中运行,但在函数中出现错误
- 释放错误后堆使用
- (C++)分析树以计算返回错误值的简单算术表达式
- Project Euler问题4的错误解决方案
- 我的字符计数代码计算错误.为什么
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 尝试导入pybind-opencv模块时出现libgtk错误
- CMake项目Boost库错误:Boost/config/compiler/gcc.hpp:165:10:致命错误:cs
- 在某些循环内使用vector.push_back时出现分段错误
- MSVC多行宏编译器错误
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 错误:未在此范围内声明'reverse'