用c语言编写一个函数,求一个整数的平方根
时间: 2024-06-09 16:09:30 浏览: 19
以下是使用牛顿迭代法实现求解整数的平方根的C语言函数:
```c
#include <stdio.h>
float sqrt(int n) {
float x = n;
float y = 1;
float e = 0.000001; // 精度
while (x - y > e) {
x = (x + y) / 2;
y = n / x;
}
return x;
}
int main() {
int n;
printf("请输入一个整数:");
scanf("%d", &n);
printf("%d 的平方根为 %f\n", n, sqrt(n));
return 0;
}
```
在函数中,我们将整数转换为浮点数,并用x初始化。然后,我们使用牛顿迭代法来逼近平方根,直到x和y之间的差小于给定的精度。最后,我们返回x的值作为结果。
相关问题
用c语言编写一个判断素数的函数
好的,以下是一个用 C 语言编写的判断素数的函数:
```c
#include <stdio.h>
#include <stdbool.h>
bool is_prime(int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
int main() {
int num;
printf("请输入一个整数:");
scanf("%d", &num);
if (is_prime(num)) {
printf("%d是素数\n", num);
} else {
printf("%d不是素数\n", num);
}
return 0;
}
```
这个函数的思路是,如果输入的数小于等于1,则不是素数;否则,从2开始到num的平方根的整数部分,逐一判断是否是num的因子,如果是,则不是素数,否则是素数。
用c语言编写函数求 N 个给定整数的均方差。
好的,这个问题是可以回答的。求 N 个给定整数的均方差,可以先求出这 N 个整数的平均值,然后再将每个数与平均值之差的平方求和,最后除以 N,就可以得到均方差了。以下是一个用C语言编写的求均方差的函数:
```c
#include <math.h>
double mean(double arr[], int n) {
double sum = 0;
for (int i = 0; i < n; i++) {
sum += arr[i];
}
return sum / n;
}
double variance(double arr[], int n) {
double m = mean(arr, n);
double sum = 0;
for (int i = 0; i < n; i++) {
sum += pow(arr[i] - m, 2);
}
return sum / n;
}
double stddev(double arr[], int n) {
return sqrt(variance(arr, n));
}
```
其中,mean函数用来求平均值,variance函数用来求方差,stddev函数用来求标准差(也就是均方差的平方根),可以根据需要选择使用。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.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)