【问题标题】:Not counting number of perfect numbers within a range?不计算一个范围内的完美数字的数量?
【发布时间】:2018-11-16 19:12:21
【问题描述】:

我想找到一个范围内的完美数字的数量。 这是我到目前为止所做的。

#include <iostream>

using namespace std;

int main()
{
   // cout<<"Hello World";
   int sum = 0;
   int count = 0;
   int x,y;
   cout<<"Enter the first number";
   cin>> x;
   cout<<"Enter the second number";
   cin>>y;
   for(int i=x;i<=y;i++)
   {
       for(int j=1; j<i; j++)
       {
           if(i%j == 0)
           {
               sum=sum+j;
           }
       }
       if(sum == i)
       {
           count++;
       }
   }
   cout<<"The number of pefect numbers are: "<<count;


}

但是当我输入范围时,它告诉我在 1 - 10 范围内可用的完美数字的数量是 0。

这是为什么呢?我不知道这里出了什么问题?

【问题讨论】:

    标签: c++ math numbers perfect-numbers


    【解决方案1】:

    需要为每个输入创建sum=0。例如

    if(sum == i) {
          count++;
    }
    sum = 0; /* add this line here */
    

    或者

    for(int i=x;i<=y;i++) {
            sum = 0; /* or make sum as 0 here  */
            for(int j=1; j<i; j++) { 
                    if(i%j == 0) {
                            sum=sum+j;
                    }
            }
            if(sum == i) {
                    count++;
            }
    }
    

    另请阅读Why is “using namespace std” considered bad practice?

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-24
    • 1970-01-01
    • 1970-01-01
    • 2013-07-18
    • 2021-10-27
    • 1970-01-01
    相关资源
    最近更新 更多