(2)编写一个在一行中连续输出指定个数字符的函数,并在主函数中调用它输出如下图案: * *** ***** ******* ***** *** * (3)写一个判定素数的函数,在主函数输入一个整数,输出是否素数的信息。
时间: 2023-09-02 07:05:43 浏览: 56
(2)函数代码如下:
```python
def print_pattern(n):
for i in range(1, n+1):
print(" "*(n-i) + "*"*(2*i-1) + " "*(n-i))
```
在主函数中调用:
```python
print_pattern(4)
```
输出如下所示:
```
*
***
*****
*******
*****
***
*
```
(3)函数代码如下:
```python
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5)+1):
if n % i == 0:
return False
return True
```
在主函数中调用:
```python
n = int(input("请输入一个整数:"))
if is_prime(n):
print("{}是素数。".format(n))
else:
print("{}不是素数。".format(n))
```
相关问题
编写一个在一行中连续输出指定个数字符的函数,并在主函数中调用它输出如下图案:
以下是实现该功能的代码:
```c
#include <stdio.h>
void printChars(int n, char c) {
for (int i = 0; i < n; i++) {
printf("%c", c);
}
}
int main() {
printChars(5, '*');
printf("\n");
printChars(4, '*');
printChars(2, ' ');
printChars(4, '*');
printf("\n");
printChars(3, '*');
printChars(4, ' ');
printChars(3, '*');
printf("\n");
printChars(2, '*');
printChars(2, ' ');
printChars(2, '*');
printChars(2, ' ');
printChars(2, '*');
printf("\n");
printChars(1, '*');
printChars(4, ' ');
printChars(1, '*');
printChars(4, ' ');
printChars(1, '*');
printf("\n");
return 0;
}
```
输出结果:
```
*****
**** ****
*** ***
** **
* *
```
编写一个在一行中连续输出指定个数字符的函数,并在主函数中调用它输出图形
以下是一个在一行中连续输出指定个数字符的函数:
```c
void printChars(int num, char c) {
for(int i = 0; i < num; i++) {
printf("%c", c);
}
}
```
接下来,我们可以在主函数中调用该函数来输出图形。例如,以下代码可以输出一个矩形:
```c
int main() {
int width = 10;
int height = 5;
for(int i = 0; i < height; i++) {
printChars(width, '*');
printf("\n");
}
return 0;
}
```
输出:
```
**********
**********
**********
**********
**********
```