我有這個f(x,num)=x*x-num
。應該用#define
來聲明。我應該使用mysqrt,它將計算一個數字num
的平方根。主要的,我應該讀取一個數字num
來「出現 - 顯示」變量num,mysqrt(num)和sqrt(num)。在函數mysqrt(num)中,我們給出x
和oldx
的初始值。 DO-而(| X-oldx |> 1E-15)。在我們將x
保存到oldx
之後。我們用方法x = x-f(x)/ f'(x)計算新的x。創建一個方法計算sqrt
我做錯了什麼?
#include <stdio.h>
#include <stdlib.h>
#define f(x) ((x) * (x) - (num))
#define fdx(x) (2 * (x))
double mysqrt(double num);
main() {
double num;
printf("the num is ", &num, &sqrt);
system("Pause");
} //end main
double mysqrt(double num) { //method
double x = 3; // i dont know if i did good i gave 3 a random number from my mind
double oldx = 1; // the same and here i did i gave a random number
double result;
double residual;
unsigned double iterations = 0;
result = sqrt(num);
x = num/2; /* initial guess */
printf("sqrt(%g)=%.16g\n", num, result);
do {
printf("x%u=%.16g\n", iterations, x);
iterations++;
oldx = x;
// x=x-f(x)/f'(x)
x = x - f(x)/fdx(x);
residual = x - oldx;
} while (fabs(residual) > 1e-15);
printf("x%u=%.16g residual=%.16g\n", iterations, x, residual);
return x;
}
當你不在循環中使用它時,保存'oldx = x;'有什麼意義? –
你能提供一些關於它不工作的信息嗎?你遇到錯誤還是結果錯誤? – jhhoff02
不要使用宏(n'inline')函數也可以!如果你老師告訴你:改變課程,他顯然不會教授現代C語言或現代編程技術。 – Olaf