读书人

人生第一次发帖就问个弱智有关问题好

发布时间: 2012-04-19 14:36:43 作者: rapoo

人生第一次发帖就问个弱智问题,好吧,关于递归函数溢出的问题……
#include "stdafx.h"
#include<iostream>
using namespace std;
long function(long a,long b,long n);
long a,b,n;
int main()
{
while(cin>>a>>b>>n&&(a||b||n)!=0)

cout<<function(a,b,n)%7<<endl;

return 0;
}

long function(long a,long b,long n)
{
if(n==1||n==2)

return 1;

else

return(a*function(a,b,n-1)+b*function(a,b,n-2));

} 就这段简单的代码,在自己电脑上运行没问题,提交的时候会提示溢出……貌似可以用循环做,但是实在想不出来,希望有高银可以帮我解决,或者解决这个溢出问题……小弟谢过先……

[解决办法]
溢出的问题对于递归函数来说是不可避免的,就算你把栈的大小改大了,递归层次过多还是一样出问题,所以要彻底的解决溢出问题的话,还是别用递归函数。
[解决办法]
这个是编译选项,你可以查查看。。不同编译器不一样
vc的是 /F<num> set stack size

探讨

引用:

把stacksize 搞大点


看不懂,不知道怎么弄,小弟我才大一,这东西书上好像木有啊,我去网上搜来学习下……

[解决办法]
仅供参考
C/C++ code
#include <stdio.h>#include <stdlib.h>#include <conio.h>#include <graphics.h>int xs[10000];int ys[10000];int i=0,xx,yy;int fc,bc;void push(int x,int y) {    xs[i]=x;    ys[i]=y;    if (i<10000-1) {        i=i+1;    } else {        printf("stack overflow!\n");        exit(1);    }}void pop(void) {    i=i-1;    xx=xs[i];    yy=ys[i];}int check(int x,int y) {    int c;    c=getpixel(x,y); /* 获取当前点的颜色 */    return ((c!=bc)&&(c!=fc));/* 如果颜色为边界色或填充色则不填充 */}void seedfilling(int x,int y,int fill_color,int boundary_color) {    fc=fill_color;    bc=boundary_color;    push(x,y);    while (1) {        if (i<=0) return;        pop();        if (check(xx,yy)) {            putpixel(xx, yy, 14);getch();  /* 加上这行显示当前填充状态 */            putpixel(xx, yy, fill_color); /* 画点 */            if (check(xx-1,yy  )) push(xx-1,yy  );            if (check(xx  ,yy+1)) push(xx  ,yy+1);            if (check(xx  ,yy-1)) push(xx  ,yy-1);            if (check(xx+1,yy  )) push(xx+1,yy  );            /* 去掉下面四句就是四连通 */            if (check(xx-1,yy-1)) push(xx-1,yy-1);            if (check(xx-1,yy+1)) push(xx-1,yy+1);            if (check(xx+1,yy-1)) push(xx+1,yy-1);            if (check(xx+1,yy+1)) push(xx+1,yy+1);        }    }}void main() {    int a,b,color;    int gdriver = DETECT, gmode, errorcode;    int poly[10];    initgraph(&gdriver, &gmode, "d:\\bc\\bgi");    a=150;    b=140;    color=4;    poly[0]=110;/* 第一个点的x坐标以及y坐标 */    poly[1]=110;    poly[2]=200;/* 第二点 */    poly[3]=105;    poly[4]=170;/* 第三点 */    poly[5]=120;    poly[6]=150;/* 第四点 */    poly[7]=170;    poly[8]=110;/* 多边形的起点与终点一样 */    poly[9]=110;    drawpoly(5,poly);/* 显示各点连接起来的多边形 */    /* 保证边界对八连通是封闭的 */    setviewport(0,1,600,300,0);    drawpoly(5,poly);/* 显示各点连接起来的多边形 */    setviewport(1,0,600,300,0);    drawpoly(5,poly);/* 显示各点连接起来的多边形 */    setviewport(1,1,600,300,0);    drawpoly(5,poly);/* 显示各点连接起来的多边形 */    /* 恢复默认viewport */    setviewport(0,0,600,300,0);    seedfilling(a,b,color,15);  /* 种子填充多边形 */    getch();    closegraph();} 

读书人网 >C++

热点推荐