【问题标题】:For loop format in CC中的for循环格式
【发布时间】:2013-07-29 13:18:23
【问题描述】:

我想知道这个程序是如何执行的并且没有抛出任何错误。

void main( ) 
{ 
    clrscr();
    int i ; 
    for ( i = 1 ; i <= 5 ; printf ( "\n%c", 65 ) ) ; 
        i++ ;
    getch(); 
} 

循环继续打印 A 永远。 for循环的格式是

for(initialize value; test counter; increment value)
{
    do this;
    and this;
    and this;
}

我的问题是 printf("\n %c", 65) 如何增加值?

【问题讨论】:

  • i++ 无法访问。
  • printf 成功返回写入的字符总数。它没有增加i
  • 谁给了你这个棘手的代码?
  • 为什么要让你的生活复杂化?删除; 后,将i++ 放在应有的位置。不要做奇怪的事情,没有人会爱你。
  • 分号被视为循环体。根据(C99, 6.8.3p3) "A null statement (consisting of just a semicolon) performs no operations."

标签: c for-loop


【解决方案1】:

for() 后面的; 导致ifor 内没有递增,从而导致无限循环。

这个:

for ( i = 1 ; i <= 5 ; printf ( "\n%c", 65 ) ) ; 
    i++ ;

相当于:

for ( i = 1 ; i <= 5 ; printf ( "\n%c", 65 ) ) {} /* Empty loop body. */
i++ ;

永远无法到达i++。要更正,请删除结尾的 ;。使用i++ 作为for 循环中的迭代表达式会更清楚,而不是printf()i 不需要存在于循环体之外:

for (int i = 1; i <= 5; i++)
{
    printf ( "\n%c", 65 );
}

我的问题是printf("\n %c", 65) 如何增加值?

printf() 返回写入的字符数,因此如果您愿意,可以使用它来增加 i,但有必要更改终止条件以考虑 \n 字符:

for (int i = 1; i <= 10; i+= printf("\n%c", 65));

但是,这比之前的建议不太清楚。

【讨论】:

    【解决方案2】:

    for ( i = 1 ; i &lt;= 5 ; printf ( "\n%c", 65 ) ) ; 本身就是一个语句 i 在这个语句中没有递增,所以无限循环。

    这称为空循环:它类似于空 for 循环。

    没有无限循环

    for ( i = 1 ; i <= 5 ; printf ( "\n%c", 65 ) ){
       i++;
    } 
    

    【讨论】:

      【解决方案3】:

      随便写

      void main( ) 
      { 
          clrscr();
          int i ; 
          for ( i = 1 ; i <= 5 ; printf ( "\n%c", 65 ) ) 
              i++ ;
          getch(); 
      } 
      

      你很高兴

      【讨论】:

        【解决方案4】:

        因为,如上所述,i++ 是不可访问的,因为“;”在 for 语句之后等于带有空白正文的 for。

        你可以这样写这个循环:

        for ( i = 1 ; i <= 5 ; printf ( "\n%c", 65 ) , i++);
        

        为了获得相同的效果并且无需编写显式块。

        【讨论】:

          【解决方案5】:

          你自己给for loop的格式是

          for(initialize value; test counter; increment value)
          {
              do this;
              and this;
              and this;
          }
          

          但是你用过

          for(initialize value; test counter; increment value);
          {
             do this;
             and this;
             and this;
          }
          

          for() 之后放置; 将导致执行空语句。这将不允许程序增加i---导致无限循环。

          【讨论】:

            【解决方案6】:
            for(initialize value; condition; increment value/decrement value)
            {
                do this;
                and this;
                and this;
            }
            you can write many initializations, many increments/decrements but we have to write only one condition 
            

            i.e( i = 1 ; i

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2013-11-05
              • 1970-01-01
              • 1970-01-01
              • 2023-01-02
              • 2022-10-20
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多