C 我需要为学校做一个节目;给定一个数,确定其素因子之和;但我不知道';我不明白为什么我的程序没有';行不通
我不明白为什么它不起作用。当我运行程序时,它告诉我和等于0C 我需要为学校做一个节目;给定一个数,确定其素因子之和;但我不知道';我不明白为什么我的程序没有';行不通,c,C,我不明白为什么它不起作用。当我运行程序时,它告诉我和等于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 t
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);
}
}
intmain(){
系统(“CLS”);系统(“颜色0a”);
int i,num,j,cont=0,somma=0;
printf(“输入一个数字”);//用户输入一个数字
scanf(“%d”和&num);
for(i=2;ifor和if后面的花括号仅在使用多个语句时才需要,但作为初学者,您应该学会始终使用它们,除非您有像if(i==0)这样的单行语句j=1;
。即使不需要缩进,也要注意缩进。它会使程序的结构在第一眼就看得更清楚。而且它很重要
然后,您应该学会非常谨慎地使用短变量名:for(j=2;jfor(j=2;i至少有一个问题:if(cont==0)somma=somma+i;
:这里您使用的是未初始化的somma
。somma
的初始值是不确定的。您可能应该在声明时将其初始化为0,就像您使用cont
时一样。我复制程序时出错,应该是j您错过了最后一个}
在你的代码中。如果
看起来很奇怪,那么在中还有额外的作用域。你想对用户输入的数字之间的所有素数求和吗?请确保更好地解释你试图达到的目标是什么?转储代码并没有帮助我们帮助你,但是我不理解一些事情。我已经调整了(j=2;j p.s ty)!
int main() {
int i,num,j,cont,somma=0;
printf("enter a number");
scanf("%d",&num);
//printf("Processing %d\n", 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:%d\n", 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;
}