企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
# C 程序:显示两个间隔之间的质数 > 原文: [https://www.programiz.com/c-programming/examples/prime-number-intervals](https://www.programiz.com/c-programming/examples/prime-number-intervals) #### 在此示例中,您将学习如何打印用户输入的两个数字之间的所有质数。 要理解此示例,您应该了解以下 [C 编程](/c-programming "C tutorial")主题: * [C `if...else`语句](/c-programming/c-if-else-statement) * [C `for`循环](/c-programming/c-for-loop) * [C `break`和`continue`](/c-programming/c-break-continue-statement) * * * ## 显示两个间隔之间的质数 ```c #include <stdio.h> int main() { int low, high, i, flag; printf("Enter two numbers(intervals): "); scanf("%d %d", &low, &high); printf("Prime numbers between %d and %d are: ", low, high); // iteration until low is not equal to high while (low < high) { flag = 0; // ignore numbers less than 2 if (low <= 1) { ++low; continue; } // if low is a non-prime number, flag will be 1 for (i = 2; i <= low / 2; ++i) { if (low % i == 0) { flag = 1; break; } } if (flag == 0) printf("%d ", low); // to check prime for the next number // increase low by 1 ++low; } return 0; } ``` **输出** ```c 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`。 访问此页面以了解有关如何[检查数字是否为质数](https://www.programiz.com/c-programming/examples/prime-number)的更多信息。 如果用户首先输入较大的数字,则上述程序将无法正常工作。 您可以通过[交换数字](https://www.programiz.com/c-programming/examples/swapping)来解决此问题。 * * * ## 首先输入较大的数字时显示质数 ```c #include <stdio.h> int main() { int low, high, i, flag, temp; printf("Enter two numbers(intervals): "); scanf("%d %d", &low, &high); // swap numbers if low is greather than high if (low > high) { temp = low; low = high; high = temp; } printf("Prime numbers between %d and %d are: ", low, high); while (low < high) { flag = 0; // ignore numbers less than 2 if (low <= 1) { ++low; continue; } for (i = 2; i <= low / 2; ++i) { if (low % i == 0) { flag = 1; break; } } if (flag == 0) printf("%d ", low); ++low; } return 0; } ``` 访问此页面以了解如何通过创建用户定义的函数来[显示两个时间间隔之间的所有质数](https://www.programiz.com/c-programming/examples/prime-interval-function)。