【发布时间】:2016-01-14 22:36:31
【问题描述】:
该程序应该提示输入一系列数字,然后为该范围内的数字吐出杂耍序列,但每当我输入超过 40 的范围时,我都会收到堆栈溢出错误,不知道为什么谢谢 “juggler_seq.exe 中 0x77354A3E (ntdll.dll) 处的未处理异常:0xC00000FD:堆栈溢出(参数:0x00000001、0x00092FF4)。”
// juggler_seq.cpp : 定义控制台应用程序的入口点。 //
#include "stdafx.h"
// Example program
#include <iostream>
#include <string>
#include <math.h>
#include <sstream>
#include <list>
template <typename T>
std::string to_string(T value){
std::ostringstream os;
os << value;
return os.str();
}
std::string jugglers(long int n, std::string ans = ""){
std::string num;
if (n == 1){
//checks for base case if 1 returns the seqence of numbers
return ans + "1";
}
else{
//checks for even odd
if (n % 2 == 0){
ans = ans + to_string(n) + ",";
//ans now adjusted to include most recent number calculated in the sequence
return jugglers(long int(pow(n, (1.0 / 2.0))), ans);
//passes the most recent number into the funtion again until the sequence converges to 1
//also passes the string ans with all previous numbers in sequence to keep track of numbers in the sequence
}
else{
num = to_string(n);
ans = ans + to_string(n) + ",";
return jugglers(long int(pow(n, (3.0 / 2.0))), ans);
}
}
}
int main()
{
int s, e;
int high = 0;
std::string usrstr;
std::list<std::string> ans;
std::list<std::string>::iterator it;
std::string n;
std::stringstream ss;
std::cout << "whats the starting point: ";
getline(std::cin, usrstr);
std::stringstream(usrstr) >> s;
std::cout << "\nwhats the end point: ";
getline(std::cin, usrstr);
std::stringstream(usrstr) >> e;
for (long int y = s; y != e + 1;y++){
ans.push_back(jugglers(y));
}
std::string com = "";
int count = 0;
int ref = 0;
for (it = ans.begin(); it != ans.end(); it++){
std::cout << *it<<std::endl;
std::string a = *it;
if (a.size()>com.size()){
com = a;
ref = count;
}
count += 1;
}
std::cout << "the ref is: " << ref + s << " the answer is : " << com << "\n";
return 0;
}
【问题讨论】:
-
通常堆栈溢出是由于超出数组末尾或执行太多递归调用引起的。您的第一步是使用内置调试器或 gdb 缓慢而痛苦地逐步完成您自己的代码,并找出它发生的位置以及原因。 :-) 玩得开心!这就是编程的全部意义所在。好吧,有一个很酷的程序也有帮助。但是找到这些错误也很有趣。 :-)
-
使用您最喜欢的调试器单步调试代码并检查 a) 是否一切正常,b) 递归深度是否变大,c)
n是否变大。 -
您使用
n^1/2递归调用偶数,使用n^3/2调用奇数。在堆栈溢出之前,它们不会在奇数和偶数之间翻转吗? -
juggler sequence 可能会导致一些非常大的数字。例如,从 37 开始,达到的最大值为 24906114455136。因此,系统上的
long至少需要为 64 位。即使这样,我也不认为使用pow会起作用,因为double只有大约16 位的精度。
标签: c++ runtime-error overflow