作业帮 > 综合 > 作业

C语言问题,迭代法求一个正数a的算术平方根的迭代公式为:在时计算的xn+1值就为数a的算术平方根.需要你计算的数a从标准

来源:学生作业帮 编辑:拍题作业网作业帮 分类:综合作业 时间:2024/04/29 20:09:46
C语言问题,迭代法
求一个正数a的算术平方根的迭代公式为:
在时计算的xn+1值就为数a的算术平方根.需要你计算的数a从标准输入,可能有多个测试用例,以最后一行为0表示结束,计算每个计算的结果使用一行输出,结果保留6位小数.输入样例和样例输出的结果如下所示:
样例输入:
3
2
0
样例输出:
1.732051
1.414214
#include
#include
#include
#define CALLOC(ARRAY,NUM,TYPE)\x05\
\x05ARRAY = (TYPE*) calloc(NUM,sizeof(TYPE));\x05\
if (ARRAY == NULL) {\x05\
\x05printf("File:%s,Line:%d:",__FILE__,__LINE__); \
\x05printf("Allocating memory failed.\n");\x05\
\x05exit(0);\x05\
}
#define REALLOC(ARRAY,NUM,TYPE)\x05\
\x05ARRAY = (TYPE*) realloc(ARRAY,(NUM)*sizeof(TYPE));\x05\
if (ARRAY == NULL) {\x05\
\x05printf("File:%s,Line:%d:",__FILE__,__LINE__); \
\x05printf("Allocating memory failed.\n");\x05\
\x05exit(0);\x05\
}
int calcsqrt(double* sqrta,int n,double* a)
{
\x05int i;
\x05double xp,xn;
\x05
\x05for (i=0; i 1e-6);
\x05\x05sqrta[i] = xn;
\x05}
\x05return 0;
}
int main()
{
\x05double* a = NULL;
\x05double* sqrta = NULL;
\x05int n = 0;
\x05double tmp;
\x05int i;
\x05printf("Please input a series of positive numbers,0 to end:\n");
\x05while(1) {
\x05\x05scanf("%lf",&tmp);
\x05\x05if (tmp>0) {
\x05\x05\x05n++;
\x05\x05\x05REALLOC(a,n,double);
\x05\x05\x05a[n-1] = tmp;
\x05\x05} else if (tmp==0) {
\x05\x05\x05break;
\x05\x05} else {
\x05\x05\x05printf("The number must be greater or equal to 0.\n");
\x05\x05}
\x05}
\x05CALLOC(sqrta,n,double);
\x05calcsqrt(sqrta,n,a);
\x05for (i=0; i
再问: 能写简单点吗
再答: 可以稍微简单一点,不用那么多宏定义,但这样就使得程序分配内存失败时,无法正常运行。代码如下: #include #include #define ABS(X) (X)>0 ? (X) : -(X) int calcsqrt(double* sqrta, int n, double* a) { int i; double xp, xn; for (i=0; i 1e-6); sqrta[i] = xn; } return 0; } int main() { double* a = NULL; double* sqrta = NULL; int n = 0; double tmp; int i; printf("Please input a series of positive numbers, 0 to end:\n"); while(1) { scanf("%lf", &tmp); if (tmp>0) { n++; a = (double*) realloc(a, n*sizeof(double)); a[n-1] = tmp; } else if (tmp==0) { break; } else { printf("The number must be greater or equal to 0.\n"); } } sqrta = (double*) calloc(n, sizeof(double)); calcsqrt(sqrta, n, a); for (i=0; i