int Fun(int m); int main() { int num; printf("Please input a number:\n"); while (scanf("%d", &num) != 1 || num <= 1) { printf("Invalid input. Please input a positive integer greater than 1:\n"); while (getchar() != '\n'); } if (Fun(num)) { printf("%d is a prime number\n", num); } else { printf("%d is not a prime number\n", num); } return 0; } int Fun(int m) { for (int i = 2; i * i <= m; i++) { if (m % i == 0) { return 0; } } return 1; }该代码有错误,多打印了 Invalid input. Please input a positive integer greater than 1:
时间: 2024-01-13 21:02:25 浏览: 25
抱歉,我没有注意到这个问题。这个问题是因为在输入不合法的情况下,程序在使用 `scanf()` 函数读取输入后,可能会留下一个换行符在输入缓冲区中,导致后续的 `getchar()` 函数读取到这个换行符而继续执行。为了避免这个问题,我们可以在 `scanf()` 函数之后加上一个 `getchar()` 函数,将输入缓冲区中的换行符读取并丢弃掉。以下是修改后的代码:
```c
#include <stdio.h>
int Fun(int m);
int main() {
int num;
printf("Please input a number:\n");
while (scanf("%d", &num) != 1 || num <= 1) {
printf("Invalid input. Please input a positive integer greater than 1:\n");
while (getchar() != '\n');
getchar(); // 读取并丢弃输入缓冲区中的换行符
}
if (Fun(num)) {
printf("%d is a prime number\n", num);
} else {
printf("%d is not a prime number\n", num);
}
return 0;
}
int Fun(int m) {
for (int i = 2; i * i <= m; i++) {
if (m % i == 0) {
return 0;
}
}
return 1;
}
```
现在,当输入不合法时,程序会使用 `getchar()` 函数将输入缓冲区中的换行符读取并丢弃掉,确保程序可以正确地等待用户重新输入。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)