简体   繁体   English

while 循环具有终止标志仍然运行良好

[英]while loop has terminating sign still works well

I was implementing Newton Raphson method in C. The code work well.我正在用 C 实现 Newton Raphson 方法。代码运行良好。 There is no error in the code.代码中没有错误。

#include<stdio.h>
#include<math.h>
#define  f(x)(x * sin(x)+cos(x))
#define df(x)(x*cos(x))
int main()
{
   float x,h,e;
   e=0.0001;
   printf("Enter the initial value of x:\n");
   scanf("%f",&x);
 do
  {
     h=-f(x)/df(x);
     x=x+h;
  }
  while(fabs(h)>e);
  printf("The value of the root is=%f",x);
  return(0);
 }
/*
Output:
Enter the initial value of x: 3
The value of the root is = 2.798386

However, I was surprised I mean how did this code work?但是,我很惊讶我的意思是这段代码是如何工作的? As per c rule while statement does not have any terminating semicolon.根据 c 规则,while 语句没有任何终止分号。 However, in my code while(fabs(h)>e);但是,在我的代码中while(fabs(h)>e); has a semicolon yet it run well.有一个分号但它运行良好。

Can anyone tells me how does it work?谁能告诉我它是如何工作的?

What you mean is putting你的意思是放

while(...);
{
//some code
}

that will be interpreted as这将被解释为

while(...){
   //looping without any instruction (probably an infinite loop)
}
{
//some code that will be executed once if the loop exits
}

do-while loop has the code executed before the condition (so at least once differently from simple while loop). do-while循环在条件之前执行代码(因此至少与简单的 while 循环不同一次)。 The correct syntax has a semicolumn:正确的语法有一个半列:

do{
   //your code to be executed at least once
}while(...);

So the answer to your question is that :所以你的问题的答案是:

 do
  {
     h=-f(x)/df(x);
     x=x+h;
  }
  while(fabs(h)>e);

is not a while statement, it's a do-while statement.不是while语句,而是do-while语句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM