如何将所有除数存储在数组中?
此程序将显示一个数的除数,然后确定其是质数还是完美数...问题是我无法将除数的值存储在数组a中。
#include <stdio.h>
#include <stdlib.h>
int main()
{ int DivCount=0,n,i,j,a[100],sum=0;
printf("Please Enter the Number : ");
scanf("%d",&n);
for(i=1;i<=n;i++)
if (n%i==0){
a[i-1]=i;
DivCount++;
}
printf("\nThe Number Has %d divisors : ",DivCount);
for(i=0;i<DivCount;i++)
printf("%d\t",a[i]);
if (DivCount==2)
printf("\nThe Number is Prime");
else
printf("\nThe Number is NOT Prime");
for(i=0;i<DivCount;i++)
sum+=a[i];
printf("\nThe Sum of the divisors is :%d",sum);
if (sum==n)
printf("\nThe Number is Perfect");
else
printf("\nThe Number is NOT Perfect");
return 0;
}
例如(n = 6),数组应为= {1,2,3,6}
答案 0 :(得分:2)
#include <stdio.h>
#include <stdlib.h>
int main()
{ int DivCount=0,n,i,j,a[100],sum=0;
printf("Please Enter the Number : ");
scanf("%d",&n);
for(i=1;i<=n;i++)
if (n%i==0){
//a[i-1]=i; <--- check this
a[DivCount]=i;
DivCount++;
}
printf("\nThe Number Has %d divisors : ",DivCount);
for(i=0;i<DivCount;i++)
printf("%d\t",a[i]);
if (DivCount==2)
printf("\nThe Number is Prime");
else
printf("\nThe Number is NOT Prime");
for(i=0;i<DivCount;i++)
sum+=a[i];
printf("\nThe Sum of the divisors is :%d",sum);
if (sum==n)
printf("\nThe Number is Perfect");
else
printf("\nThe Number is NOT Perfect");
return 0;
}