21xrx.com
2025-03-29 11:05:55 Saturday
文章检索 我的文章 写文章
如何编写C++完数判断函数
2023-07-10 09:01:11 深夜i     44     0
C++ 完数 判断函数 编写

完数是指一个数的所有因子之和等于该数本身的数,例如6是一个完数,因为它的因子为1、2、3,而1+2+3=6。在C++中,可以通过编写函数来判断一个数是否为完数。下面是编写C++完数判断函数的步骤。

1. 定义一个函数,函数名为isPerfectNumber,参数为一个整型数n。

2. 在函数中定义变量sum,初始值为0,用于存储所有因子的和。

3. 使用for循环遍历1到n/2的整数,如果n能被i整除,则i为n的因子,将其加入sum中。

4. 判断sum是否等于n,如果是,则说明n为完数,返回true,如果不是,则说明n不是完数,返回false。

5. 在主函数中调用isPerfectNumber函数,传入需要判断的整数,根据返回值输出判断结果。

下面是完整的C++代码:

#include <iostream>
using namespace std;
bool isPerfectNumber(int n) {
  int sum = 0;
  for (int i = 1; i <= n/2; i++) {
    if (n % i == 0) {
      sum += i;
    }
  }
  if (sum == n)
    return true;
   else
    return false;
  
}
int main() {
  int n;
  cout << "请输入一个整数:";
  cin >> n;
  if (isPerfectNumber(n))
    cout << n << "是完数。" << endl;
   else
    cout << n << "不是完数。" << endl;
  
  return 0;
}

通过上面的代码,我们可以输入一个整数n,程序能够判断n是否为完数,并输出判断结果。

  
  

评论区

请求出错了