编写函数fun(),它的功能是求n以内(不包括n)同时能被5与11整 除的所有自然数之和的平方根s,并作为函数值返回。 例如:n为1000时,函数值应为s=96.979379。 注意:部分源程序给出如下。 请勿改动主函数main和其他函数中的任何内容,仅在函数 fun的花括号中填入所编写的若干语句。 请补充下列程序,使其输出正确结果。 #include <math.h> #include <stdio.h> #include <stdlib.h> double fun(int n) { double s = 0.0; int i; /**********Program**********/ /********** End **********/ } int main() { FILE *wf; system("CLS"); printf("s=%f\n", fun(1000)); wf=fopen("out.txt", "w"); fprintf(wf, "%f", fun(1000)); fclose(wf); }
时间: 2023-07-18 13:49:59 浏览: 74
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
double fun(int n) {
double s = 0.0;
int i;
for(i=1; i<n; i++) {
if(i%5==0 && i%11==0) {
s += i;
}
}
return sqrt(s);
}
int main() {
FILE *wf;
system("CLS");
printf("s=%f\n",fun(1000));
wf=fopen("out.txt","w");
fprintf(wf,"%f",fun(1000));
fclose(wf);
return 0;
}
输出结果为:
s=96.979379
相关问题
编写函数fun,它的功能是:求n以内(不包括n)同时能被3与7整除的所有自然数之和
函数fun的实现需要从1到n-1遍历所有自然数,对于每个数进行判断是否同时能被3和7整除。如果是,则将该数累加到计数变量中。代码如下:
```python
def fun(n):
count = 0 # 初始化计数变量为0
for i in range(1, n):
if i % 3 == 0 and i % 7 == 0: # 判断同时被3和7整除
count += i # 累加符合条件的数到计数变量中
return count # 返回符合条件的自然数之和
```
这个函数的时间复杂度为O(n),因为需要遍历所有自然数。在计算n较大的时候可能会比较耗时,可以考虑优化算法来减少时间复杂度。例如,可以发现,同时被3和7整除的自然数必须是21的倍数,所以可以直接初始化i为21并且每次加21进行遍历,这样可以节省一些时间复杂度。
C语言编写函数fun(),它的功能是求n以内(不包括n)同时能被5与11整 除的所有自然数之和的平方根s,并作为函数值返回。
以下是实现该函数fun()的C语言代码:
```c
#include <stdio.h>
#include <math.h>
double fun(int n) {
int sum = 0;
for (int i = 0; i < n; i++) {
if (i % 5 == 0 && i % 11 == 0) {
sum += i;
}
}
double s = sqrt(sum);
return s;
}
int main() {
int n;
printf("请输入n的值:");
scanf("%d", &n);
double result = fun(n);
printf("n以内同时能被5与11整除的数之和的平方根为:%lf", result);
return 0;
}
```
在该代码中,首先定义了一个函数fun(),它接受一个整数参数n,表示要求n以内同时能被5与11整除的数之和的平方根。在函数中,用一个for循环遍历0到n-1之间的所有自然数,若该数能同时被5和11整除,则将其加到sum变量中。最后用sqrt函数计算sum的平方根,并返回该值。
在主函数中,先读入n的值,然后调用fun()函数求解。最后将结果输出。
相关推荐
![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_column_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)
![mht](https://img-home.csdnimg.cn/images/20210720083646.png)