简体   繁体   English

一旦程序开始运行,这个循环就不会结束

[英]This loop is not ending once program starts running

Once my program starts running it is not stopping after few steps.一旦我的程序开始运行,它就不会在几步后停止。 Can anyone help me with this?谁能帮我这个?

#include <stdio.h>
void main()
{
   int n,row,column,lim1,lim2,k;
   scanf("%d",&n);
   lim2=(2*n)-1;
   lim1=1;
   k=n;
   for(row=1,column=1;row<=lim2,column<=lim2;row++,column++)
      while((row||column=lim1)||(row||column=lim2))
      { printf("%d",k);
        n--;
        lim1=lim1+1;
      }
}

Expressions of the form表格的表达

(row||column=lim1)

do not mean anything like what you appear to think they mean.不要像您认为的那样表达任何意思。

In the first place, the column=lim1 part is an assignment , not an equality test.首先, column=lim1部分是一个assignment ,而不是一个相等性测试。 Equality tests use the == operator.相等测试使用==运算符。 On the other hand, in C, assignments are expressions (they evaluate to the value assigned), so they may appear as sub-expressions of larger expressions, as here.另一方面,在 C 中,赋值是表达式(它们计算为赋值的值),因此它们可能出现为更大表达式的子表达式,如下所示。 In boolean context, the value zero represents false, and any other value represents true.在布尔上下文中,值零表示假,任何其他值表示真。 lim1 starts at 1 and counts up, so its value never evaluates to true (unless it counts up so far that it wraps back to zero). lim1从 1 开始并向上计数,因此它的值永远不会计算为 true(除非它计数到返回到零为止)。

But the more significant issue is the use of the ||但更重要的问题是||的使用operator.操作员。 My best guess is that you mean the above excerpt to express a condition that either row or column is equal to lim1 , but it doesn't mean that at all.我最好的猜测是你的意思是上面的摘录表达了一个条件,即rowcolumn等于lim1 ,但这根本不是那个意思。 Instead, it expresses the condition that either row is nonzero ( ie true) or the result of column=lim1 is nonzero.相反,它表示任row非零(真)或column=lim1的结果非零的条件。 Since row starts at 1 and is not modified in the inner loop, that overall expression will always evaluated to true.由于row从 1 开始并且在内部循环中未修改,因此整个表达式将始终评估为真。

Moreover, C guarantees that if the left-hand operand of an ||此外,C 保证如果||的左侧操作数operator evaluates to true, then the right-hand operand isn't even evaluated (since that is not needed to determine the result of the operation).运算符的计算结果为真,则甚至不计算右侧的操作数(因为确定操作结果不需要它)。

The condition you seem to want to express could be spelled like this:您似乎想要表达的条件可以这样拼写:

((row == lim1) || (column == lim1))

Similar changes are needed in the other half of the inner loop's condition.内循环条件的另一半也需要类似的更改。

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

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