2021-05-26 14:21

求C语言大佬帮忙 我是入门小白

• 点赞
• 收藏

5条回答默认 最新

• qfl_sdu 2021-05-26 14:41
已采纳

for(;;)换成whie(true)就可以了。代码如下：

``````#include <math.h>
#include <stdio.h>
#define E 0.00001
extern double f(double x);
void main()
{
double a=-3.0,b=3.0,c;
while(true) //for(;;)
{
if(fabs(b-a) < E)
break;
c=(a+b)/2.0;
if(f(c)==0.0)
break;
else if(f(a)*f(c) > 0.0)
a=c;
else b=c;
}
printf("x=%10.5f\n",c);
}
double f(double x)
{
return(x*x*x+3.0*x*x+3.0*x+1.0);
}``````
点赞 评论
• CSDN专家-link 2021-05-26 14:37

你代码里都是用break退出循环，for就是个无条件死循环，和while(true)是一样的效果，所以直接换成while(true)就满足你需求了

点赞 评论
• CSDN专家-link 2021-05-26 14:42

如果希望while有终止条件，那么这么写

``````#define E 0.00001
extern double f(double x);
void main()
{
double a = -3.0, b = 3.0, c = (a + b) / 2.0;;
while ((fabs(b - a) >= E) && f(c) != 0)
{
if(f(a)*f(c) > 0.0)
a=c;
else
b=c;
c = (a + b) / 2;
}
printf("x=%10.5f\n",c);
}
double f(double x)
{
return(x*x*x+3.0*x*x+3.0*x+1.0);
}``````
点赞 评论
• 秋杪 2021-05-26 14:28
``````while(abs(b-a) < E || f(c)==0.0)

{

c=(a+b)/2.0;

if(f(a)*f(c) > 0.0)

a=c;

else

b=c;

}``````
点赞 评论
• 铭睿科技老郭 2021-05-26 14:37
`````` #include #include
#define E 0.00001  extern double f(double x);
void main() {
double a=-3.0,b=3.0,c;
while(abs(b-a) < E || f(c) == 0.0){
c = (a + b) / 2.0;
if(f(a) * f(c) > 0.0){
a = c;
}else{
b = c;
}
printf("x=%10.5f\n",c);
}
double f(double x) {
return(x*x*x+3.0*x*x+3.0*x+1.0);
}``````

你原代码的include导入库应该有问题，记得回去贴回原来的库

点赞 评论