# C++ 程序：显示两个间隔之间的质数

> 原文： [https://www.programiz.com/cpp-programming/examples/prime-number-intervals](https://www.programiz.com/cpp-programming/examples/prime-number-intervals)

#### 在 C++ 编程中打印两个数字（由用户输入）之间的所有质数的示例。 使用嵌套的`for`循环和`if...else`语句可以解决此问题。

要理解此示例，您应该了解以下 [C++ 编程](/cpp-programming "C++ tutorial")主题：

*   [C++ `if`，`if...else`和嵌套`if...else`](/cpp-programming/if-else)
*   [C++ `for`循环](/cpp-programming/for-loop) 
*   [C++ `break`和`continue`语句](/cpp-programming/break-continue)

* * *

* * *

## 例 1：显示两个间隔之间的质数

```cpp
#include <iostream>
using namespace std;

int main()
{
    int low, high, i, flag;

    cout << "Enter two numbers(intervals): ";
    cin >> low >> high;

    cout << "Prime numbers between " << low << " and " << high << " are: ";

    while (low < high)
    {
        flag = 0;

        for(i = 2; i <= low/2; ++i)
        {
            if(low % i == 0)
            {
                flag = 1;
                break;
            }
        }

        if (flag == 0)
            cout << low << " ";

        ++low;
    }

    return 0;
} 
```

**输出**

```cpp
Enter two numbers(intervals): 20 50 Prime numbers between 20 and 50 are: 23 29 31 37 41 43 47
```

在此程序中，`while`循环被迭代`(high - low - 1)`次。

在每次迭代中，检查`low`是否是质数，然后将`low`的值增加 1，直到`low`等于`high`。

访问此页面以了解有关如何[检查数字是否为质数](/cpp-programming/examples/prime-number "C check prime number")的更多信息。

如果用户首先输入较大的数字，则该程序无法正常工作。 如果用户先输入较大的数字，则可以通过[交换数字](/cpp-programming/examples/swapping "swap numbers in C programming")来解决此问题。

* * *

## 例 2：首先输入较大的数字时显示质数

```cpp
#include <iostream>
using namespace std;

int main()
{
    int low, high, flag, temp;

    cout << "Enter two numbers(intevals): ";
    cin >> low >> high;

    //swapping numbers if low is greater than high
    if (low > high) {
        temp = low;
        low = high;
        high = temp;
    }
    cout << "Prime numbers between " << low << " and " << high << " are: ";

    while (low < high)
    {
        flag = 0;

        for(int i = 2; i <= low/2; ++i)
        {
            if(low % i == 0)
            {
                flag = 1;
                break;
            }
        }
        if (flag == 0)
            cout << low << " ";

        ++low;
    }
    return 0;
} 
```

访问此页面以了解如何使用用户定义的函数来[显示两个时间间隔之间的所有质数](/cpp-programming/examples/prime-interval-function)。