奇葩的数组越界


已解决:http://bbs.csdn.net/topics/390881205?page=1#post-398149811


题目大意:

求1-1000以内的所有完数,并输出其因子

例6=1+2+3,故6是完数


Error原因:!!! 在main函数里申明一个数组int k[11];(用于存下所有的因子),在gcc(code::block 10.05)下能编译通过,且能输出正确结果,在中间调试的时候明显能看到k数组越界!!但是!!把k数组增大,例如k[20],程序会挂在a=420的地方,而把k数组申明在main函数外 或者 在main函数内申明一个比较大的数组,则不会挂掉


为毛 int k[11] 就可以哪!!


代码如下:

 

#include<iostream>
#include<stdio.h>

using namespace std;
//int k[2];

int main()
{

    int n,i,a,temp;
    int k[11];
    //int k[20];
    for(a=2;a<=1000;a++){
        n=0; temp=a;
        for(i=1;i<=a/2;i++)
            if(a%i==0)
            {
                n++;
                k[n]=i;
                temp=temp-i;
                //printf("k_%d=%d ",n,k[n]);
                //cout<<endl;
            }
       //cout<<"n="<<n<<endl;
        //cout<<"a="<<a<<endl;
        /* if(a==419){
            cout<<temp<<endl;
            for(i=1;i<=n;i++)
                cout<<k[i]<<" ";
            cout<<endl;
        }
        cout<<n<<endl;
        */
        if(temp==0)
        {
            cout<<a<<" is a 完数"<<endl;
            cout<<"its factors are:";

            for(i=1;i<n;i++)
                cout<<k[i]<<",";

            cout<<k[n]<<endl<<endl;
        }
    }
    return 0;
}


 

posted @ 2014-09-08 23:08  某某璀  阅读(203)  评论(0编辑  收藏  举报
levels of contents