an exercise:find out the perfect number from 1 to 1000 (perfect number:such as 6,because 6=1+2+3) this is my code.
#include<iostream>
using namespace std;
int main()
{
int k[11];
int i, a, n, s;
for (a = 2; a <= 1000; a++)
{
n = 0;
s = a;
for (i = 1; i < a; i++)
if (a%i == 0)
{
n++;
s = s - i;
k[n] = i;
}
if (s == 0)
{
cout << a << " is a perfect number" << endl;
cout << "its factors are:";
for (i = 1; i <= n; i++)cout << k[i] << " ";
cout << endl;
}
}
return 0;
}
but it shows Run-Time Check Failure #2 - Stack around the variable 'k' was corrupted when I change int k[11]
to int k[32]
it is correct.
the array element is at least 32 ,so why?
Array indices start at 0. You are incrementing n too early. And obviously, 10 is too small as the array size. What formula gives this size?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.