我无法将我的代码与除数相加 [英] I couldn't make my code sum the divisors
本文介绍了我无法将我的代码与除数相加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使一个程序从键盘获取最大数量(n)并找到从1到n的每个整数的除数和除数之和,当我没有使用我的代码的总和部分时它打印得很完美,但是当我尝试用总和进行打印时,它会给出错误的数字:
它完美地运作:
I was making a program takes maximum number (n) from keyboard and finds the divisors and sum of this divisors for each integer from 1 to n,when i didn't use the sum part of my code it prints perfectly, but when i try to print with sum it gives wrong numbers:
it works perfectly :
<pre>int main()
{
int x,n,sum,c;
printf("Enter a maximum number :");
scanf("%d",&n);
for(c=1;c<=n;c++)
{
for (x = 1; x <= c; x++)
{
if(c%x == 0)
{
printf("%d ",x);
}
}
printf("\n");
}
}
我尝试过:
当我尝试添加总和时它会给出错误的数字:
What I have tried:
when i try this to add sum part it gives wrong numbers:
int main()
{
int x,n,sum,c;
printf("Enter a maximum number n :");
scanf("%d",&n);
for(c=1;c<=n;c++)
{
for (x = 1; x <= c; x++)
{
if(c%x == 0)
{
printf("%d ",x);
sum=0;
sum=sum+x;
printf("%d",sum);
}
}
printf("\n");
}
推荐答案
嗯......调试器会很快向你展示问题,但你应该能够看到快速浏览一下代码吧。
Well... the debugger would show you the problem pretty quickly, but you should be able to see it yourself with a quick glance over the code.
for (x = 1; x <= c; x++)
{
if(c%x == 0)
{
printf("%d ",x);
sum=0;
sum=sum+x;
printf("%d",sum);
}
提示:当您尝试向其添加最新值时, sum
的值是多少?
移动一行代码将修复它。
Hint: what is the value of sum
when you try to add the latest value to it?
Moving one line of code will fix it.
这篇关于我无法将我的代码与除数相加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文