2014-07-04 52 views
-1

我正在編寫一些代碼作爲一些作業的一部分,以從絕對基本知識中學習C編程,而且我遇到了一個問題,可能很簡單解決,但我完全卡住了!我正在編寫一個程序來實現基本的牛頓分化方法。每當我向scanf()輸入一個初始值時,程序就會停止,不會返回任何東西,終止或凍結。任何幫助都會很棒。 這裏是我的代碼開始:爲scanf()輸入一個值,但沒有任何反應

#include <stdio.h> 
    #include <stdlib.h> 
    #include <math.h> 

//function to be used f(x) = cos(x)-x^3 

//f'(x) = -sin(x)-3x^2 

int main() 
{ 
    double x, xold; 
    printf("Enter an initial value between 0 and 1\n"); 
    scanf("%lf",&xold); 
    double eps = 1e-12; 
    x = xold - ((cos(xold)-pow(xold,3))/(-(sin(xold)-(3*pow(xold,2))))); 
    while (fabs(x-xold)>eps) 
    { 
    x = xold - ((cos(xold)-pow(xold,3))/(-sin(xold)-(3*pow(xold,2)))); 
    } 
    printf("The answer is %.12lf",x); 
    return 0; 
}; 

回答

2

在while循環:

x = xold - ((cos(xold)-pow(xold,3))/(-sin(xold)-(3*pow(xold,2)))); 

=右操作數的值總是相同的,你怎麼可能,一旦你進入它退出循環?

+0

啊好吧,我試圖讓它將新的x更改爲xold,然後重試它。任何想法我會怎麼做?對不起,這實際上是我第一次完成編碼haha – alexheslop1

+0

+1,好趕上! –

0

其實事情是你沒有更新你的xold變量。嘗試下面的修改後的代碼爲您的問題,看看我是否做得正確:

#include <stdio.h> 
#include <stdlib.h> 
#include <math.h> 


int main() 
{ 
    double x, xold; 
    printf("Enter an initial value between 0 and 1\n"); 
    scanf("%lf",&x); 
    double eps = 1e-12; 

    x = x - ((cos(x)-pow(x,3))/(-(sin(x)-(3*pow(x,2))))); 
    while (fabs(x - xold)>eps) 
    { 
     xold = x; 
     x = x - ((cos(x)-pow(x,3))/(-sin(x)-(3*pow(x,2)))); 
    } 
    printf("The answer is %.12lf\n",x); 

    return 0; 
}