企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持知识库和私有化部署方案 广告
# C++ 程序:使用函数显示两个时间间隔之间的质数 > 原文: [https://www.programiz.com/cpp-programming/examples/prime-interval-function](https://www.programiz.com/cpp-programming/examples/prime-interval-function) #### 通过创建用户定义的函数来打印两个数字(由用户输入)之间的所有质数的示例。 要理解此示例,您应该了解以下 [C++ 编程](/cpp-programming "C++ tutorial")主题: * [C++ `for`循环](/cpp-programming/for-loop) * [C++ `break`和`continue`语句](/cpp-programming/break-continue) * [C++ 函数](/cpp-programming/function) * [C++ 中用户定义函数的类型](/cpp-programming/user-defined-function-types) * * * * * * ## 示例:两个间隔之间的质数 ```cpp #include <iostream> using namespace std; int checkPrimeNumber(int); int main() { int n1, n2; bool flag; cout << "Enter two positive integers: "; cin >> n1 >> n2; cout << "Prime numbers between " << n1 << " and " << n2 << " are: "; for(int i = n1+1; i < n2; ++i) { // If i is a prime number, flag will be equal to 1 flag = checkPrimeNumber(i); if(flag) cout << i << " "; } return 0; } // user-defined function to check prime number int checkPrimeNumber(int n) { bool flag = true; for(int j = 2; j <= n/2; ++j) { if (n%j == 0) { flag = false; break; } } return flag; } ``` **输出** ```cpp Enter two positive integers: 12 55 Prime numbers between 12 and 55 are: 13 17 19 23 29 31 37 41 43 47 53 ``` 要打印两个整数之间的所有质数,将创建`checkPrimeNumber()`函数。 此函数[检查数字是否为质数](/cpp-programming/examples/prime-number "Example to check prime number in C++")。 `n1`和`n2`之间的所有整数都传递给此函数。 如果传递给`checkPrimeNumber()`的数字是质数,则此函数返回`true`,否则返回`false`。 如果用户首先输入较大的数字,则该程序将无法正常工作。 要解决此问题,您需要先[交换数字](/cpp-programming/examples/swapping "C++ program to swap numbers")。