输入若干个单词,输出它们的平均长度,保留两位小数。单词只包含大写字母和小写字母,单词前后都可能有一个或者多个空格隔开。请使用循环和数组实现。
时间: 2023-08-19 20:02:16 浏览: 247
### 回答1:
首先,需要将输入的字符串按照空格分割成单词,并存储到数组中。可以使用split()方法实现。
然后,遍历数组,计算每个单词的长度,并累加到总长度中。
最后,将总长度除以单词个数,保留两位小数即可得到平均长度。
以下是示例代码:
```python
words = input().split() # 输入并分割单词
total_length = # 总长度
word_count = len(words) # 单词个数
for word in words:
total_length += len(word) # 计算每个单词的长度并累加到总长度中
avg_length = total_length / word_count # 计算平均长度
print('%.2f' % avg_length) # 输出结果,保留两位小数
```
注意,输出结果时需要使用格式化字符串来保留两位小数。
### 回答2:
首先,我们可以将输入的字符串按照空格进行分割,得到一个包含所有单词的数组。然后,使用循环遍历该数组,累加每个单词的长度。最后,将累加结果除以单词的个数,得到平均长度,并保留两位小数输出。
具体步骤如下:
1. 获取输入的字符串,假设存储在变量input_str中。
2. 定义一个空数组words,用于存储分割后的单词。
3. 使用split()方法将输入的字符串按照空格进行分割,并将结果存储到数组words中。
4. 定义一个变量total_length,初始值为0,用于累加单词的长度。
5. 使用循环遍历数组words,对每个单词进行操作。
1)对于每个单词,使用len()方法获取其长度,并将结果累加到total_length中。
6. 定义变量avg_length,将total_length除以单词的个数,得到平均长度。
7. 格式化输出平均长度,保留两位小数。
代码如下:
```python
input_str = input("请输入若干个单词:")
words = input_str.split()
total_length = 0
for word in words:
total_length += len(word)
avg_length = total_length / len(words)
print("平均长度为:{:.2f}".format(avg_length))
```
使用示例:
输入:Hello World!
输出:平均长度为:5.00
### 回答3:
要实现输入若干个单词,输出它们的平均长度,我们可以按照以下步骤进行:
1. 首先,提示用户输入若干个单词。
2. 使用input()函数获取用户输入,并将输入的字符串按空格进行分割得到单词列表。
3. 创建一个名为lengths的空数组,用于存放每个单词的长度。
4. 使用循环遍历单词列表,对于每个单词,使用len()函数获取其长度,并添加到lengths数组中。
5. 定义一个变量total_length,并初始化为0,用于记录所有单词的总长度。
6. 使用循环遍历lengths数组,将每个单词长度累加到total_length中。
7. 计算平均长度,将total_length除以单词个数得到结果,保留两位小数。
8. 输出平均长度。
下面是实现这个功能的示例代码:
```python
# 提示用户输入若干个单词
words = input("请输入若干个单词,以空格分隔:")
# 分割输入的字符串得到单词列表
word_list = words.split()
# 创建一个空数组用于存放单词长度
lengths = []
# 遍历单词列表,获取每个单词的长度,并添加到lengths数组中
for word in word_list:
word_length = len(word)
lengths.append(word_length)
# 计算单词总长度
total_length = sum(lengths)
# 计算平均长度
average_length = total_length / len(word_list)
# 输出平均长度,保留两位小数
print("平均长度为:{:.2f}".format(average_length))
```
这样,就可以通过循环和数组实现输入若干个单词,输出它们的平均长度,并且保留两位小数。
相关推荐
![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)