开发者

Finding Local maximum in C

I would like to find the local maximum within the interval of 0 to 3.1416 for this Sin(x) function. But it shows always 0 as the maximum value.i.e The maximum value=0; Please help me finding my faults.

thanks.

#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#ifndef max
    #define max(a,b) ((a)>(b)?(a):(b))
#endif
double f(double x){
return sin(x);
}
double bisection(double a,double b)
{
double Fa=f(a);
double Fb=f(b);
double midpoint=(a+b)/2;
double Fmidpoint=f(midpoint);
while(abs(b-a)>1e-6){
double left=(a+midpoint)/2;
double right=(b+midpoint)/2;
double Fleft=f(left);
double Fright=f(right);
if(midpoint>max(Fleft,Fright)){
    a=left;
   开发者_Go百科 Fa=Fleft;
    b=right;
    Fb=Fright;
}
else{
    if(Fleft>Fright)
    {
        b=midpoint;
        Fb=Fmidpoint;
        midpoint=left;
        Fmidpoint=Fleft;
    }
    else{
        a=midpoint;
        Fa=Fmidpoint;
        midpoint=right;
        Fmidpoint=Fright;
    }
}
}
return midpoint;
}
int main(){
double maximum;
double rangeleft=0;
double rangeright=3.1416;
maximum=bisection(rangeleft,rangeright);
printf("%d",maximum);
return 0;
}


You have an error in calling the printf function.

You should not use %d format identifier here because it means that printf should output an integer while your maximum variable is double.

Use %f instead and your program will output 1.5708 which is correct.

You can find the list of all possible printf format identifiers on Wikipedia.


If you would debug it, you could see that variables has correct value, so problem must by in the printing this value %d makes from your double - integer - use %f

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜