有一个定义在正数上的函数 fun(x) 定义如下: 若 x <10 , 则 fun(x) = x。 若 10<=x<=20, 则 fun(x) = -x。 若 x>20, 则 fun(x) = x*3。 试用c++编写该函数,输入x值,返回相应的fun(x)值。
时间: 2023-11-23 09:05:56 浏览: 156
以下是使用C语言编写的函数:
```c
#include <stdio.h>
float fun(float x) {
if (x < 10) {
return x;
} else if (x <= 20) {
return -x;
} else {
return x * 3;
}
}
int main() {
float x;
printf("请输入x值:");
scanf("%f", &x);
printf("fun(x)的值为:%f", fun(x));
return 0;
}
```
在该程序中,使用了if-else语句来判断x的范围,并返回相应的fun(x)值。在主函数中,先输入x的值,再调用fun函数来计算fun(x)的值,并输出结果。
相关问题
编写函数fun,统计一组不少于 10个数的正数个数,并计算其 平均值
好的,以下是函数 `fun` 的实现:
```python
def fun(nums):
"""
统计一组不少于10个数的正数个数,并计算其平均值
:param nums: 一个包含数字的列表
:return: 返回正数个数和平均值,以元组的形式返回
"""
positive_count = 0
positive_sum = 0
for num in nums:
if num > 0:
positive_count += 1
positive_sum += num
if positive_count == 0:
return 0, 0
else:
return positive_count, positive_sum / positive_count
```
这个函数接受一个包含数字的列表 `nums` 作为参数,遍历这个列表,统计其中正数的个数和总和,最后计算平均值并返回。如果列表中没有正数,则返回 `(0, 0)`。
C语言编写函数fun,统计一组不少于10个数的正数个数,并计算其平均值。
可以使用如下的C语言代码实现:
```c
#include <stdio.h>
// 声明函数fun
void fun(int arr[], int len);
int main() {
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; // 数组中至少有10个数
int len = sizeof(arr) / sizeof(arr[0]); // 数组长度
fun(arr, len);
return 0;
}
// 定义函数fun
void fun(int arr[], int len) {
int count = 0; // 正数个数
int sum = 0; // 所有正数的和
for (int i = 0; i < len; i++) {
if (arr[i] > 0) {
count++;
sum += arr[i];
}
}
float avg = (float)sum / count; // 计算平均值
printf("正数个数为:%d\n", count);
printf("平均值为:%f\n", avg);
}
```
在上面的代码中,我们先声明了一个函数`fun`,然后在主函数`main`中定义了一个包含至少10个数的数组,并将其作为参数传递给`fun`函数。在`fun`函数中,我们使用一个循环遍历数组中的所有数,当遇到正数时,将其个数和值分别累加到计数器`count`和累加器`sum`中。最后,我们通过计算`sum`和`count`的商来得到正数的平均值,并在屏幕上输出。注意,在计算平均值时,需要将其中一个操作数强制转换为`float`类型,以避免整数除法的问题。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)