我需要为学校做一个程序"给定一个数字建立其素数除数的总和",但我不明白为什么我的程序不起作用



我不明白为什么它不起作用。当我运行程序时,它告诉我总和等于 0。

int main()  {
system("CLS"); system("COLOR 0a");
int i,num,j,cont=0,somma=0;
printf("enter a number");       //the user enter a number
scanf("%d",&num);
for(i=2;i<=num;i++)      //the for and the if detects all divisors of the number entered except 1
if(num%i==0){ 
for(j=2;j<i;i++) //this for and if detect the divisors of the divisor of the entered number
if(i%j==0)
cont++; 
{
if(cont==0) //if cont == 0 the divisor of the number is prime and is added to the sum
somma=somma+i;
}
printf("the sum of the prime divisor of %d is %d",num,somma);
}
}

只有在使用多个语句时才需要 for 和 if 后面的大括号,但作为初学者,您应该学会始终使用它们,除非您有像if (i == 0) j=1;这样的单行语句。即使不需要注意压痕。它将使程序的结构一目了然。这很重要...

然后你应该学会非常谨慎地使用短变量名:for(j=2;j<i;i++)递增i何时应该递增j

最后,您应该始终想知道应该在什么时候初始化变量。您可以在双循环中使用cont,并且仅在程序开始时将其初始化为 0。应在外部循环的每次迭代中将其重置为 0。

最后但并非最不重要的一点是:学习使用调试器,或在整个代码中使用跟踪打印语句。如果你有,问题将是不言而喻的——事实上我做到了......

解决所有这些问题,程序应该给出预期的结果。或者问一个新的问题,如果它仍然坏了。但是当它起作用时,我强烈建议您将其发布在代码审查中。你会在C语言部分和算法部分得到很好的建议。


下面是代码的最小固定版本,其中包含有助于识别问题的(注释掉的(跟踪:

int main()  {
int i,num,j,cont,somma=0;
printf("enter a number");
scanf("%d",&num);
//printf("Processing %dn", num);
for(i=2;i<=num;i++) {
//printf("i:%d", i);
if(num%i==0){
cont = 0;          // must be reset to 0 for every i
for(j=2;j<i;j++) {
//printf("j:%dn", j);
if(i%j==0) cont++;
}
if(cont==0) somma=somma+i;
}
}
printf("the sum of the prime divisor of %d is %d",num,somma);
return 0;
}

请不要盲目使用它,而是尝试了解差异,不要忘记代码审查步骤......

相关内容

最新更新