主函数输入一个正整数,通过调用函数来判断此数是不是既能被5整除,又能被7整除,并输出结果
时间: 2023-11-27 21:04:13 浏览: 52
可以使用以下代码实现:
```python
def is_divisible_by_5_and_7(num):
if num % 5 == 0 and num % 7 == 0:
return True
else:
return False
num = int(input("请输入一个正整数:"))
if is_divisible_by_5_and_7(num):
print(f"{num}既能被5整除,又能被7整除")
else:
print(f"{num}不能同时被5和7整除")
```
首先定义了一个函数 `is_divisible_by_5_and_7` ,该函数接受一个参数 `num` ,判断 `num` 是否同时能被5和7整除。如果能,返回 `True` ,否则返回 `False` 。
在主函数中,先输入一个正整数 `num` ,然后调用 `is_divisible_by_5_and_7` 函数来判断 `num` 是否能同时被5和7整除。如果能,输出结果为“`num` 既能被5整除,又能被7整除”,否则输出结果为“`num` 不能同时被5和7整除”。
相关问题
用c语言实现主函数输入一个正整数,通过调用函数来判断此数是不是既能被5整除,又能被7整除,并输出结果
以下是用C语言实现主函数输入一个正整数,通过调用函数来判断此数是不是既能被5整除,又能被7整除,并输出结果的代码:
```c
#include <stdio.h>
int is_divisible_by_5_and_7(int n) {
if (n % 5 == 0 && n % 7 == 0) {
return 1;
} else {
return 0;
}
}
int main() {
int n;
printf("请输入一个正整数:");
scanf("%d", &n);
if (is_divisible_by_5_and_7(n)) {
printf("%d 既能被5整除,又能被7整除。\n", n);
} else {
printf("%d 不能同时被5和7整除。\n", n);
}
return 0;
}
```
代码解释:
首先定义了一个判断一个正整数是否既能被5整除,又能被7整除的函数 `is_divisible_by_5_and_7`,接受一个参数 n,如果 n 能同时被 5 和 7 整除,则返回 1,否则返回 0。
在主函数中,首先要求用户输入一个正整数 n,并将其保存到变量 `n` 中。然后调用函数 `is_divisible_by_5_and_7` 判断 n 是否能同时被 5 和 7 整除,如果能,则输出结果,否则输出另一种结果。最后返回 0,表示程序正常结束。
写一个判素数的函数,在主函数输入一个正整数,调用该函数判断它是否是素数,然后在主函数中输出结果:"是素数",或者"不是素数"。
以下是使用C++编写的判断素数的函数代码:
```cpp
#include <iostream>
using namespace std;
bool isPrime(int n) {
if (n < 2) { // 小于2的数不是素数
return false;
}
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) { // 如果能被i整除,不是素数
return false;
}
}
return true;
}
int main() {
int n;
cout << "请输入一个正整数: ";
cin >> n;
if (isPrime(n)) {
cout << n << " 是素数" << endl;
} else {
cout << n << " 不是素数" << endl;
}
return 0;
}
```
首先,`isPrime`函数接受一个正整数作为参数,如果这个数小于2,则直接返回`false`,因为小于2的数不是素数。接下来,我们使用一个循环,从2开始枚举所有小于等于n的整数,如果n能被其中的一个整数i整除,则n不是素数,返回`false`。最后,如果循环结束后没有返回`false`,则n是素数,返回`true`。
在主函数中,我们先输入一个正整数n,然后调用`isPrime`函数判断它是否是素数,根据函数的返回值输出结果。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![c](https://img-home.csdnimg.cn/images/20210720083646.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)