21xrx.com
2024-06-03 09:13:34 Monday
登录
文章检索 我的文章 写文章
自定义C++程序求完数
2023-07-05 07:11:19 深夜i     --     --
C++ 自定义 完数 程序 求解

完数是指一个数等于其因子之和(不包括其自身)。例如,6是一个完数,因为6 = 1 + 2 + 3。如果一个数不等于其因子之和,那么它就不是完数。

在C++编程语言中,我们可以使用自定义函数来判断一个给定的数是否为完数。该函数接受一个整数作为输入,并返回一个布尔值,指示该数是否为完数。

下面是一个简单的自定义函数求完数:


bool isPerfect(int num){

  int sum = 0;

  for (int i = 1; i < num; i++) {

    if (num % i == 0) {

      sum += i;

    }

  }

  if (sum == num)

    return true;

  

  else

    return false;

  

}

该函数计算输入数字num的因子和,并将其与num进行比较。如果它们相等,则该数是完数,返回true。否则不是完数,返回false。

现在,我们可以编写一个程序,来打印给定范围内的完数。


#include <iostream>

using namespace std;

bool isPerfect(int num);

int main()

{

  int startRange, endRange;

  cout << "Enter the starting number of the range: ";

  cin >> startRange;

  cout << "Enter the ending number of the range: ";

  cin >> endRange;

  cout << "Perfect numbers between " << startRange << " and " << endRange << " are: " << endl;

  for (int i = startRange; i <= endRange; i++) {

    if (isPerfect(i))

      cout << i << endl;

    

  }

  return 0;

}

bool isPerfect(int num){

  int sum = 0;

  for (int i = 1; i < num; i++) {

    if (num % i == 0) {

      sum += i;

    }

  }

  if (sum == num)

    return true;

  

  else

    return false;

  

}

在这个程序中,我们要求用户输入范围的起始和结束数字。然后,我们使用for循环来遍历给定范围内的数字。使用isPerfect函数来判断数字是否为完数,如果是,则打印该数字。

这个程序可以帮助我们快速找到在给定范围内的完数,并为我们提供了有关C++程序的基本编程概念,例如自定义函数和循环。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复