用c语言写程序,给定一个正整数 N,请你求 N 的立方根是多少输入描述:第 1 行为一个整数 T,表示测试数据的数量,接下来的 T 行每行包含一个正整数 N。1≤T≤100000,0≤N≤100000输出描述:多行,每行包括一个答案(答案保留3 位有效数字)和计算该答案的循环次数
时间: 2024-11-09 07:23:26 浏览: 39
在C语言中,为了求解一个正整数N的立方根并提供循环次数,你可以使用牛顿迭代法(也称为二分法的一种变体)。下面是一个简单的示例代码:
```c
#include <stdio.h>
#include <math.h>
#define PRECISION 0.0001
double cubeRoot(double n, int* iterations) {
double guess = n / 3;
*iterations = 0;
while (fabs(guess * guess * guess - n) > PRECISION) {
guess = (guess + n / guess) / 2;
(*iterations)++;
}
return guess;
}
int main() {
int t;
scanf("%d", &t);
for (int i = 0; i < t; i++) {
long long n;
scanf("%lld", &n);
if (n <= 0) {
printf("Invalid input! N should be a positive integer.\n");
} else {
int iterations;
double result = cubeRoot((double)n, &iterations);
printf("%.3lf (computed in %d iterations)\n", result, iterations);
}
}
return 0;
}
```
在这个程序中,`cubeRoot` 函数接受一个正实数 `n` 和一个指向整数的指针 `iterations`,用于记录循环次数。函数使用牛顿迭代法逐步逼近立方根,并检查每次迭代后的误差是否小于预设精度 `PRECISION`。
在主函数 `main` 中,读入测试数据的数量 `t`,然后遍历每个测试用例,计算并打印出立方根及其所需的迭代次数。对于非正整数,程序会给出错误提示。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![ppt](https://img-home.csdnimg.cn/images/20241231044937.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)