【问题标题】:while loop has terminating sign still works wellwhile 循环有终止符号仍然可以正常工作
【发布时间】:2021-01-06 21:30:55
【问题描述】:

我在 C 中实现 Newton Raphson 方法。代码运行良好。代码没有错误。

#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

但是,我很惊讶我的意思是这段代码是如何工作的?根据 c 规则,while 语句没有任何终止分号。但是,在我的代码中 while(fabs(h)>e); 有一个分号,但它运行良好。

谁能告诉我它是如何工作的?

【问题讨论】:

  • 这不是while-loop。
  • 另外,“per c rule”while(x); 是一个有效的声明。相当于while(x) {}

标签: c while-loop semicolon-inference


【解决方案1】:

你的意思是放

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

这将被解释为

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

do-while 循环在条件之前执行代码(因此与简单的 while 循环至少有一次不同)。正确的语法有一个分列:

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

【讨论】:

    【解决方案2】:

    所以你的问题的答案是:

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

    不是while 语句,而是do-while 语句。

    【讨论】:

      猜你喜欢
      • 2013-04-22
      • 1970-01-01
      • 1970-01-01
      • 2014-04-30
      • 2015-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多