【问题标题】:Find sum of factors of given integer and divide it by the given integer求给定整数的因子之和并将其除以给定整数
【发布时间】:2018-10-07 17:15:28
【问题描述】:

我是 C 语言的新手,我真的可以在这个问题上寻求帮助:

整数的丰度定义为一个数的完美除数(不包括数本身的因子)除以数本身。例如,8 的丰度为 (1+2+4)/8 = 7/8。编写一个 C 函数,将单个整数作为输入并返回该数字的丰度。

这是我所知道的。我可以编译它,但我一直得到不正确的答案。请帮助并提前感谢

#include <stdio.h>
int main()
{
    int number, i, sum, abundancy;
    sum==0;
    abundancy==0;

    printf("Enter an integer:");
    scanf("%d", &number);

    for(i=1; i<=number; i++)
    {
        if (i!=number)
        {
            if (number%i == 0)
            {
                sum+=i;
                    {
                        abundancy=sum/number;
                        printf("The abundancy is %d", abundancy);
                    }
            }
        }
    }
    return 0;
}
  • 这是我在在线编译器上得到的

  • 这是我编译时得到的

【问题讨论】:

  • sum==0; abundancy==0; 不分配 0。阅读有关 == 运算符的信息,对于分配,您应该使用 =
  • abundancy=sum/number; 导致int 因此7/80
  • 谢谢!正如你所说,我已经将 sum==0 和 abundancy==0 更改为 sum=0 和 abundancy =0。但是对于第二部分,我不确定如何纠正它,但我明白你的意思,我对此仍然很陌生,所以我不知道如何纠正它。

标签: c loops if-statement factors


【解决方案1】:

您在循环中执行abundancy=sum/number;,这将获取错误的结果。这是您的代码的正确版本以及更改:

#include <stdio.h>
int main()
{
    int number, i, sum, abundancy;
    sum=0;                       //USE ASSIGNMENT NOT EQUAL TO OPERATOR
    abundancy=0;                 //USE ASSIGNMENT NOT EQUAL TO OPERATOR

    printf("Enter an integer:");
    scanf("%d", &number);

    for(i=1; i<number; i++)                 //CHANGED
    {
        if (number%i == 0)              //ONLY SINGLE IF NEEDED
        {
            sum+=i;
        }
    }
    abundancy = sum/number;
    printf("Abundancy is: %d/%d\n",sum,number);   //ADDED 
    printf("abundancy is: %d\n",abundancy);

    return 0;
}

即使这样 abundancy 将包含 sum/number 的底值 - 您应该在打印时使用 float%f 作为格式说明符。

输入:

12

输出:

 abundancy is: 16/12
 abundancy is: 1

【讨论】:

  • 您好,非常感谢!它的工作原理天哪。但是为什么我不需要 if(i!=number) 呢?
  • @Christine 因为问题陈述说factors not including the number itself - 为此我已经修改了for 循环,使用&lt;number 而不是&lt;=number
  • 抱歉,我刚刚意识到您更改了 for 循环中的条件,因此您不必执行 if(i!=number)。再次感谢:)
  • @Christine 既然它有帮助,你可能想访问这个:stackoverflow.com/help/someone-answers :) 欢迎来到 SO
猜你喜欢
  • 2012-01-28
  • 1970-01-01
  • 2021-09-04
  • 1970-01-01
  • 2018-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-05
相关资源
最近更新 更多