作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在努力完成作业,但有些事情困住了我。
问题来了:在N范围内,按如下格式输出因数之和等于其自身的数。
输入:
1000
输出:
6 its factors are 1 2 3
28 its factors are 1 2 4 7 14
496 its factors are 1 2 4 8 16 31 62 124 248
这是我的代码,请告诉我为什么我不能得到正确的输出。欣赏它,如果你可以帮我改进它。
提前致谢。
#include<stdio.h>
#define NUM 100
int main()
{
int goal[NUM];//array for factors.
int N;
scanf("%d",&N);
getchar();
for(int p=2;p<N;p++)//1 and N are not included.
{
int j=0,sum=0;
for(int i=1;i<p; )
{
//get factors and put them into array.
while(p%i==0)
{
goal[j]=i;
sum+=goal[j];
j++;
i++;
}
}
//judge the sum of factors and p the two values are equal.
if(sum==p)
{
printf("%d its factors are ",p);
for(int i=0;i<j;i++)
{
while(i==j-1)
printf("%d \n",goal[i]);
}
}
}
return 0;
}
最佳答案
让其变得干净一点,
int main()
{
int N, factors_sum, factors_cnt, num, j;
scanf("%d", &N);
int *factors = malloc(sizeof(int) * N/2);
if (factors == NULL)
{
perror("malloc(2)");
return 1;
}
for (num = 2 ; num < N ; ++num)
{
factors_cnt = 0;
factors_sum = 0;
for (j = 1 ; j <= num/2 ; ++j)
if (num % j == 0)
factors_sum += (factors[factors_cnt++] = j);
if (factors_sum == num)
{
printf("%d its factors are", num);
for (j = 0 ; j < factors_cnt ; ++j)
printf(" %d", factors[j]);
printf("\n");
}
}
free(factors);
return 0;
}
保留代码的修改:
#include<stdio.h>
#define NUM 100
int main()
{
int goal[NUM];//array for factors.
int sum=0;
int N;
scanf("%d",&N);
//getchar(); // I donno why you need this, better to remove it
for(int p=2;p<N;p++)//1 and N are not included.
{
// sum is different for every number
// need to be set to 0 individually for every number
sum = 0;
int j=0;
for(int i=1;i<p; i++) // i++ everytime
{
//get factors and put them into array.
if (p%i==0)
// changed while to if
// while would keep executing forever
{
goal[j]=i;
sum+=goal[j];
j++;
}
}
//judge the sum of factors and p the two values are equal.
if (sum==p)
{
printf("%d its factors are ",p);
for(int i=0;i<j;i++)
{
// no need for while here
printf("%d \n",goal[i]);
}
}
}
return 0;
}
我已对您的代码进行了修改,并纠正/评论了您所犯的错误。
关于c - 寻找等于自己个数的因数之和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58102879/
我制作了一个函数,可以一次绘制来自多个因子分析的载荷,也可以绘制变量不完全重叠(或根本不重叠)的载荷。它可以正常工作,但有时在各个分析中因子加载是相同的,这意味着这些点会相互重叠绘制。 library
我是一名优秀的程序员,十分优秀!