源代码如下:#include <stdio.h>
int main()
{
int i,j,m,k,l=0;
int a[20];
for(i=2;i<=1000;i++)
{k=0;
for(j=1;j<i;j++)
{
if(i%j==0)
{a[k]=j;
l+=a[k];
k++;
}}
if(l==i)
{
printf("%d its facrors are",i);
for(m=0;a[m+1]=='\0';m++)
printf("%d,",a[m]);
printf("%d\n",a[m]);
}
}
return 0;
}
为什么每次一运行就停止工作?到底是哪里的问题?求指导啊
3 个解决方案
#1
设个断点调试。
l += a[k];这句话中k越界了,你数组a只有20个空间,k远远大于20
l += a[k];这句话中k越界了,你数组a只有20个空间,k远远大于20
#2
if (l == i)
{
printf("%d its facrors are", i);
for (m = 0; m<k; m++)
printf("%d,", a[m]);
{
printf("%d its facrors are", i);
for (m = 0; m<k; m++)
printf("%d,", a[m]);
#3
修改如下:
int main()
{
int i, j, m, k, l;
//int a[20];
int a[1000];
for (i = 2; i <= 1000; i++)
{
k = l = 0;
memset(a, 0, sizeof(int) * 1000);
for (j = 1; j < i; j++)
{
if (i % j == 0)
{
a[k] = j;
l += a[k];
k++;
}
}
if (l == i)
{
printf("%d its facrors are ", i);
for (m = 0; a[m + 1]; m++)
printf("%d,", a[m]);
printf("%d\n", a[m]);
}
}
return 0;
}
//6 its facrors are 1, 2, 3
//28 its facrors are 1, 2, 4, 7, 14
//496 its facrors are 1, 2, 4, 8, 16, 31, 62, 124, 248
#1
设个断点调试。
l += a[k];这句话中k越界了,你数组a只有20个空间,k远远大于20
l += a[k];这句话中k越界了,你数组a只有20个空间,k远远大于20
#2
if (l == i)
{
printf("%d its facrors are", i);
for (m = 0; m<k; m++)
printf("%d,", a[m]);
{
printf("%d its facrors are", i);
for (m = 0; m<k; m++)
printf("%d,", a[m]);
#3
修改如下:
int main()
{
int i, j, m, k, l;
//int a[20];
int a[1000];
for (i = 2; i <= 1000; i++)
{
k = l = 0;
memset(a, 0, sizeof(int) * 1000);
for (j = 1; j < i; j++)
{
if (i % j == 0)
{
a[k] = j;
l += a[k];
k++;
}
}
if (l == i)
{
printf("%d its facrors are ", i);
for (m = 0; a[m + 1]; m++)
printf("%d,", a[m]);
printf("%d\n", a[m]);
}
}
return 0;
}
//6 its facrors are 1, 2, 3
//28 its facrors are 1, 2, 4, 7, 14
//496 its facrors are 1, 2, 4, 8, 16, 31, 62, 124, 248