以下是一个判断用户输入的正整数是否为质数的 C++ 代码示例:

#include <iostream>
using namespace std;

int main() {
  int n;
  bool isPrime = true;

  cout << '请输入一个正整数:';
  cin >> n;

  // 判断n是否为质数
  for (int i = 2; i <= n / 2; ++i) {
    if (n % i == 0) {
      isPrime = false;
      break;
    }
  }

  if (isPrime)
    cout << n << ' 是质数';
  else
    cout << n << ' 不是质数';

  return 0;
}

在这个程序中,我们首先从用户那里获取一个正整数。然后,我们使用一个循环来判断这个数字是否为质数。如果 n 可以被 2 到 n/2 之间的任意整数整除,则它不是质数,程序输出'不是质数'。否则,它是质数,程序输出'是质数'。

C++ 代码:判断一个数是否为质数

原文地址: https://www.cveoy.top/t/topic/lJLD 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录