精华内容
下载资源
问答
  • Python“ while循环无限迭代)

    千次阅读 2020-07-14 22:45:54
    Iteration means executing the same block of code over and over, potentially many times. A programming structure that implements iteration is called a loop. ... 实现迭代的编程结构称为循环 。 In pr...

    Iteration means executing the same block of code over and over, potentially many times. A programming structure that implements iteration is called a loop.

    迭代意味着一次又一次地执行同一段代码。 实现迭代的编程结构称为循环

    In programming, there are two types of iteration, indefinite and definite:

    在编程中,有两种类型的迭代:不确定的和确定的:

    • With indefinite iteration, the number of times the loop is executed isn’t specified explicitly in advance. Rather, the designated block is executed repeatedly as long as some condition is met.

    • With definite iteration, the number of times the designated block will be executed is specified explicitly at the time the loop starts.

    • 对于不确定的迭代 ,循环的执行次数没有事先明确指定。 相反,只要满足某些条件,就会重复执行指定的块。

    • 通过确定的迭代 ,指定的块将在循环开始时明确执行的次数。

    In this tutorial, you’ll:

    在本教程中,您将:

    • Learn about the while loop, the Python control structure used for indefinite iteration
    • See how to break out of a loop or loop iteration prematurely
    • Explore infinite loops
    • 了解while循环,这是用于不确定迭代的Python控制结构
    • 了解如何提前退出循环或循环迭代
    • 探索无限循环

    When you’re finished, you should have a good grasp of how to use indefinite iteration in Python.

    完成后,您应该掌握如何在Python中使用不确定的迭代。

    Free Bonus: Click here to get our free Python Cheat Sheet that shows you the basics of Python 3, like working with data types, dictionaries, lists, and Python functions.

    免费红利: 单击此处可获得我们的免费Python备忘单 ,其中显示了Python 3的基础知识,例如使用数据类型,字典,列表和Python函数。

    while循环 (The while Loop)

    Let’s see how Python’s while statement is used to construct loops. We’ll start simple and embellish as we go.

    让我们看看如何使用Python的while语句构造循环。 我们将以简单而优美的方式开始。

    The format of a rudimentary while loop is shown below:

    基本的while循环的格式如下所示:

     while while << exprexpr >> :
        :
        << statementstatement (( ss )) >
    >
    

    <statement(s)> represents the block to be repeatedly executed, often referred to as the body of the loop. This is denoted with indentation, just as in an if statement.

    <statement(s)>表示要重复执行的块,通常称为循环的主体。 就像if语句一样,用缩进表示。

    Remember: All control structures in Python use indentation to define blocks. See the discussion on grouping statements in the previous tutorial to review.

    切记: Python中的所有控件结构都使用缩进来定义块。 请参阅上一教程中有关分组语句的讨论。

    The controlling expression, <expr>, typically involves one or more variables that are initialized prior to starting the loop and then modified somewhere in the loop body.

    控制表达式<expr>通常涉及一个或多个变量,这些变量在启动循环之前已初始化,然后在循环主体中的某处进行了修改。

    When a while loop is encountered, <expr> is first evaluated in Boolean context. If it is true, the loop body is executed. Then <expr> is checked again, and if still true, the body is executed again. This continues until <expr> becomes false, at which point program execution proceeds to the first statement beyond the loop body.

    遇到while循环时,首先在Boolean上下文中评估<expr> 。 如果为true,则执行循环体。 然后再次检查<expr> ,如果仍然为true,则再次执行主体。 这一直持续到<expr>变为false,这时程序执行将继续执行循环体之外的第一条语句。

    Consider this loop:

    考虑以下循环:

    >>>
    >>>
     >>>  n = 5
    >>>  while n > 0 :
    ...     n -= 1
    ...     print ( n )
    ...
    4
    3
    2
    1
    0
    
    

    Here’s what’s happening in this example:

    这是此示例中发生的事情:

    • n is initially 5. The expression in the while statement header on line 2 is n > 0, which is true, so the loop body executes. Inside the loop body on line 3, n is decremented by 1 to 4, and then printed.

    • When the body of the loop has finished, program execution returns to the top of the loop at line 2, and the expression is evaluated again. It is still true, so the body executes again, and 3 is printed.

    • This continues until n becomes 0. At that point, when the expression is tested, it is false, and the loop terminates. Execution would resume at the first statement following the loop body, but there isn’t one in this case.

    • n最初是5 。 第2行的while语句标头中的表达式为n > 0 ,这是正确的,因此将执行循环体。 在第3行的循环体内, n递减14 ,然后打印。

    • 循环体完成后,程序执行将返回到循环的第二行,并再次对表达式进行求值。 这仍然是正确的,因此主体再次执行,并打印了3

    • 这一直持续到n变为0为止。 此时,当测试表达式时,它为false,并且循环终止。 执行将在循环体后的第一个语句处恢复,但在这种情况下没有一个。

    Note that the controlling expression of the while loop is tested first, before anything else happens. If it’s false to start with, the loop body will never be executed at all:

    请注意,在发生其他任何事情之前,将首先测试while循环的控制表达式。 如果开头是错误的,则循环体将永远不会执行:

    >>>
    >>>
     >>>  n = 0
    >>>  while n > 0 :
    ...     n -= 1
    ...     print ( n )
    ...
    
    

    In the example above, when the loop is encountered, n is 0. The controlling expression n > 0 is already false, so the loop body never executes.

    在上面的示例中,遇到循环时, n0 。 控制表达式n > 0已经为假,因此循环体从不执行。

    Here’s another while loop involving a list, rather than a numeric comparison:

    这是涉及列表而不是数字比较的另一个while循环:

    >>>
    >>>
     >>>  a = [ 'foo' , 'bar' , 'baz' ]
    >>>  while a :
    ...     print ( a . pop ( - 1 ))
    ...
    baz
    bar
    foo
    
    

    When a list is evaluated in Boolean context, it is truthy if it has elements in it and falsy if it is empty. In this example, a is true as long as it has elements in it. Once all the items have been removed with the .pop() method and the list is empty, a is false, and the loop terminates.

    在布尔上下文中评估列表时,如果列表中包含元素,则为true;如果为空,则为false。 在此示例中,只要其中包含元素, a为真。 一旦使用.pop()方法删除了所有项目,并且列表为空,则a为false,并且循环终止。

    循环迭代中断 (Interruption of Loop Iteration)

    In each example you have seen so far, the entire body of the while loop is executed on each iteration. Python provides two keywords that terminate a loop iteration prematurely:

    到目前为止,在每个示例中, while循环的整个主体都是在每次迭代中执行的。 Python提供了两个关键字来提前终止循环迭代:

    • break immediately terminates a loop entirely. Program execution proceeds to the first statement following the loop body.

    • continue immediately terminates the current loop iteration. Execution jumps to the top of the loop, and the controlling expression is re-evaluated to determine whether the loop will execute again or terminate.

    • break立即完全终止循环。 程序执行继续到循环体后的第一条语句。

    • continue立即终止当前循环迭代。 执行跳转到循环的顶部,并重新计算控制表达式以确定循环是再次执行还是终止。

    The distinction between break and continue is demonstrated in the following diagram:

    之间的区别breakcontinue证明如下图:

    Python while循环:break和继续语句
    break and continue
    打破并继续

    Here’s a script file called break.py that demonstrates the break statement:

    这是一个名为break.py的脚本文件,用于演示break语句:

    Running break.py from a command-line interpreter produces the following output:

    从命令行解释器运行break.py会产生以下输出:

     C:UsersjohnDocuments>python break.py
    C:UsersjohnDocuments> python break.py
    4
    4
    3
    3
    Loop ended.
    Loop ended.
    

    When n becomes 2, the break statement is executed. The loop is terminated completely, and program execution jumps to the print() statement on line 7.

    n变为2 ,将执行break语句。 循环完全终止,程序执行跳至第7行的print()语句。

    The next script, continue.py, is identical except for a continue statement in place of the break:

    下一个脚本continue.py与除breakcontinue语句相同:

    The output of continue.py looks like this:

    continue.py的输出如下所示:

     C:UsersjohnDocuments>python continue.py
    C:UsersjohnDocuments> python continue.py
    4
    4
    3
    3
    1
    1
    0
    0
    Loop ended.
    Loop ended.
    

    This time, when n is 2, the continue statement causes termination of that iteration. Thus, 2 isn’t printed. Execution returns to the top of the loop, the condition is re-evaluated, and it is still true. The loop resumes, terminating when n becomes 0, as previously.

    这次,当n2continue语句导致该迭代终止。 因此,不会打印2 。 执行返回到循环的顶部,条件被重新评估,并且仍然为真。 如前所述,循环将继续,直到n变为0时终止。

    else条款 (The else Clause)

    Python allows an optional else clause at the end of a while loop. This is a unique feature of Python, not found in most other programming languages. The syntax is shown below:

    Python在while循环的结尾允许一个可选的else子句。 这是Python的独特功能,大多数其他编程语言都没有。 语法如下所示:

    The <additional_statement(s)> specified in the else clause will be executed when the while loop terminates.

    while循环终止时,将执行else子句中指定的<additional_statement(s)>

    thought balloon

    About now, you may be thinking, “How is that useful?” You could accomplish the same thing by putting those statements immediately after the while loop, without the else:

    关于现在,您可能会想,“这有什么用?” 您可以通过将这些语句立即放在while循环之后而不使用else来完成相同的事情:

     while while << exprexpr >> :
        :
        << statementstatement (( ss )) >
    >
    << additional_statementadditional_statement (( ss )) >
    >
    

    What’s the difference?

    有什么不同?

    In the latter case, without the else clause, <additional_statement(s)> will be executed after the while loop terminates, no matter what.

    在后一种情况下,没有else子句,无论循环如何, <additional_statement(s)>将在while循环终止后执行。

    When <additional_statement(s)> are placed in an else clause, they will be executed only if the loop terminates “by exhaustion”—that is, if the loop iterates until the controlling condition becomes false. If the loop is exited by a break statement, the else clause won’t be executed.

    <additional_statement(s)>放在else子句中时,仅当循环“通过穷举”终止时(即,循环迭代直到控制条件变为假),才执行它们。 如果循环由break语句退出,则else子句将不会执行。

    Consider the following example:

    考虑以下示例:

    >>>
    >>>
     >>>  n = 5
    >>>  while n > 0 :
    ...     n -= 1
    ...     print ( n )
    ...  else :
     ...     print ( 'Loop done.' )
     ...
    4
    3
    2
    1
    0
    Loop done.
    
    

    In this case, the loop repeated until the condition was exhausted: n became 0, so n > 0 became false. Because the loop lived out its natural life, so to speak, the else clause was executed. Now observe the difference here:

    在这种情况下,重复循环直到条件用尽: n变为0 ,因此n > 0变为假。 可以说,由于循环是自然的,所以执行else子句。 现在在这里观察区别:

    >>>
    >>>
     >>>  n = 5
    >>>  while n > 0 :
    ...     n -= 1
    ...     print ( n )
    ...     if n == 2 :
     ...         break
     ...  else :
    ...     print ( 'Loop done.' )
    ...
    4
    3
    2
    
    

    This loop is terminated prematurely with break, so the else clause isn’t executed.

    该循环以break提前终止,因此else子句不执行。

    It may seem as if the meaning of the word else doesn’t quite fit the while loop as well as it does the if statement. Guido van Rossum, the creator of Python, has actually said that, if he had it to do over again, he’d leave the while loop’s else clause out of the language.

    看起来单词else的含义似乎不太适合while循环,也似乎不适合if语句。 实际上,Python的创建者Guido van Rossum曾说过,如果要让它再做一遍,他会把while循环的else子句放在语言之外。

    One of the following interpretations might help to make it more intuitive:

    以下解释之一可能有助于使其更直观:

    • Think of the header of the loop (while n > 0) as an if statement (if n > 0) that gets executed over and over, with the else clause finally being executed when the condition becomes false.

    • Think of else as though it were nobreak, in that the block that follows gets executed if there wasn’t a break.

    • 将循环的标头( while n > 0 )视为一个if语句( if n > 0 ),它会一遍又一遍地执行,当条件变为false时, else子句最终会执行。

    • 想想else好像nobreak ,因为如果没有break ,紧随其后的程序段将被执行。

    If you don’t find either of these interpretations helpful, then feel free to ignore them.

    如果您对以上两种解释都没有帮助,请随时忽略它们。

    When might an else clause on a while loop be useful? One common situation is if you are searching a list for a specific item. You can use break to exit the loop if the item is found, and the else clause can contain code that is meant to be executed if the item isn’t found:

    while循环上的else子句何时有用? 一种常见情况是在列表中搜索特定项目。 如果找到该项目,则可以使用break退出循环,如果没有找到该项目,则else子句可以包含要执行的代码:

    >>>
    >>>
     >>>  a = [ 'foo' , 'bar' , 'baz' , 'qux' ]
    >>>  s = 'corge'
    
    >>>  i = 0
    >>>  while i < len ( a ):
    ...     if a [ i ] == s :
    ...         # Processing for item found
    ...         break
    ...     i += 1
    ...  else :
    ...     # Processing for item not found
    ...     print ( s , 'not found in list.' )
    ...
    corge not found in list.
    
    

    Note: The code shown above is useful to illustrate the concept, but you’d actually be very unlikely to search a list that way.

    注意:上面显示的代码对于说明该概念很有用,但是实际上不太可能以这种方式搜索列表。

    First of all, lists are usually processed with definite iteration, not a while loop. Definite iteration is covered in the next tutorial in this series.

    首先,通常使用确定的迭代while不是while循环来处理列表。 本系列的下一篇教程将介绍确定的迭代。

    Secondly, Python provides built-in ways to search for an item in a list. You can use the in operator:

    其次,Python提供了内置的方式来搜索列表中的项目。 您可以使用in运算子:

    >>>
    >>>
     >>>  if s in a :
    ...     print ( s , 'found in list.' )
    ...  else :
    ...     print ( s , 'not found in list.' )
    ...
    corge not found in list.
    
    

    The list.index() method would also work. This method raises a ValueError exception if the item isn’t found in the list, so you need to understand exception handling to use it. In Python, you use a try statement to handle an exception. An example is given below:

    list.index()方法也可以使用。 如果在列表中找不到该项目,则此方法将引发ValueError异常,因此您需要了解异常处理才能使用它。 在Python中,您可以使用try语句来处理异常。 下面是一个示例:

    >>>
    >>>
     >>>  try :
    ...     print ( a . index ( 'corge' ))
    ...  except ValueError :
    ...     print ( s , 'not found in list.' )
    ...
    corge not found in list.
    
    

    You will learn about exception handling later in this series.

    您将在本系列后面的内容中了解异常处理。

    An else clause with a while loop is a bit of an oddity, not often seen. But don’t shy away from it if you find a situation in which you feel it adds clarity to your code!

    带有while循环的else子句有点奇怪,不经常看到。 但是,如果发现这种情况会增加代码的清晰度,请不要回避它!

    无限循环 (Infinite Loops)

    Suppose you write a while loop that theoretically never ends. Sounds weird, right?

    假设您编写了一个理论上永远不会结束的while循环。 听起来很怪吧?

    Consider this example:

    考虑以下示例:

    >>>
    >>>
     >>>  while True :
    ...     print ( 'foo' )
    ...
    foo
    foo
    foo
      .
      .
      .
    foo
    foo
    foo
    KeyboardInterrupt
    Traceback (most recent call last):
      File "<pyshell#2>" , line 2 , in <module>
        print ( 'foo' )
    
    

    This code was terminated by Ctrl+C, which generates an interrupt from the keyboard. Otherwise, it would have gone on unendingly. Many foo output lines have been removed and replaced by the vertical ellipsis in the output shown.

    该代码由Ctrl + C终止,这会从键盘产生中断。 否则,它会一直持续下去。 许多foo输出行已删除,并由所示输出中的垂直省略号代替。

    Clearly, True will never be false, or we’re all in very big trouble. Thus, while True: initiates an infinite loop that will theoretically run forever.

    显然, True永远不会为假,否则我们都将面临巨大麻烦。 因此, while True:启动一个无限循环,理论上它将永远运行。

    Maybe that doesn’t sound like something you’d want to do, but this pattern is actually quite common. For example, you might write code for a service that starts up and runs forever accepting service requests. “Forever” in this context means until you shut it down, or until the heat death of the universe, whichever comes first.

    也许这听起来不像您想做的事情,但是这种模式实际上很普遍。 例如,您可能会为启动并永远运行以接受服务请求的服务编写代码。 在这种情况下,“永远”是指直到您将其关闭或直到宇宙热死为止,以先到者为准。

    More prosaically, remember that loops can be broken out of with the break statement. It may be more straightforward to terminate a loop based on conditions recognized within the loop body, rather than on a condition evaluated at the top.

    更一般地说,请记住可以使用break语句打破循环。 根据在循环体内识别的条件而不是在顶部评估的条件终止循环可能更直接。

    Here’s another variant of the loop shown above that successively removes items from a list using .pop() until it is empty:

    这是上面显示的循环的另一个变体,它使用.pop()连续从列表中删除项目,直到其为空:

    >>>
    >>>
     >>>  a = [ 'foo' , 'bar' , 'baz' ]
    >>>  while True :
    ...     if not a :
    ...         break
    ...     print ( a . pop ( - 1 ))
    ...
    baz
    bar
    foo
    
    

    When a becomes empty, not a becomes true, and the break statement exits the loop.

    a变为空时, not a变为true, break语句退出循环。

    You can also specify multiple break statements in a loop:

    您还可以在循环中指定多个break语句:

    In cases like this, where there are multiple reasons to end the loop, it is often cleaner to break out from several different locations, rather than try to specify all the termination conditions in the loop header.

    在这种情况下,有多种原因终止循环,从几个不同的位置break通常会比较干净,而不是尝试在循环头中指定所有终止条件。

    Infinite loops can be very useful. Just remember that you must ensure the loop gets broken out of at some point, so it doesn’t truly become infinite.

    无限循环可能非常有用。 只需记住,您必须确保循环在某个时刻被打破,这样才不会真正变成无限循环。

    嵌套while循环 (Nested while Loops)

    In general, Python control structures can be nested within one another. For example, if/elif/else conditional statements can be nested:

    通常,Python控件结构可以相互嵌套。 例如, if / elif / else条件语句可以嵌套:

     if if age age < < 1818 :
        :
        if if gender gender == == 'M''M' :
            :
            printprint (( 'son''son' )
        )
        elseelse :
            :
            printprint (( 'daughter''daughter' )
    )
    elif elif age age >= >= 18 18 and and age age < < 6565 :
        :
        if if gender gender == == 'M''M' :
            :
            printprint (( 'father''father' )
        )
        elseelse :
            :
            printprint (( 'mother''mother' )
    )
    elseelse :
        :
        if if gender gender == == 'M''M' :
            :
            printprint (( 'grandfather''grandfather' )
        )
        elseelse :
            :
            printprint (( 'grandmother''grandmother' )
    )
    

    Similarly, a while loop can be contained within another while loop, as shown here:

    同样, while循环可以包含在另一个while循环中,如下所示:

    >>>
    >>>
     >>>  a = [ 'foo' , 'bar' ]
    >>>  while len ( a ):
     ...     print ( a . pop ( 0 ))
    ...     b = [ 'baz' , 'qux' ]
    ...     while len ( b ):
     ...         print ( '>' , b . pop ( 0 ))
    ...
    foo
    > baz
    > qux
    bar
    > baz
    > qux
    
    

    A break or continue statement found within nested loops applies to the nearest enclosing loop:

    在嵌套循环中找到的breakcontinue语句适用于最近的封闭循环:

    Additionally, while loops can be nested inside if/elif/else statements, and vice versa:

    另外, while循环可以嵌套在if / elif / else语句中,反之亦然:

     if if << exprexpr >> :
        :
        statement
        statement
        while while << exprexpr >> :
            :
            statement
            statement
            statement
    statement
    elseelse :
        :
        while while << exprexpr >> :
            :
            statement
            statement
            statement
        statement
        statement
    statement
    

    In fact, all the Python control structures can be intermingled with one another to whatever extent you need. That is as it should be. Imagine how frustrating it would be if there were unexpected restrictions like “A while loop can’t be contained within an if statement” or “while loops can only be nested inside one another at most four deep.” You’d have a very difficult time remembering them all.

    实际上,所有Python控件结构都可以相互混合到所需的程度。 那是应该的。 想象一下,怎么折腾那将是如果有类似的限制意外“A while循环不能被包含在一个if声明”或“ while循环只能被嵌套在彼此最多四层。” 您将很难记住它们。

    Seemingly arbitrary numeric or logical limitations are considered a sign of poor program language design. Happily, you won’t find many in Python.

    似乎任意的数字或逻辑限制被认为是糟糕的程序语言设计的标志。 幸运的是,在Python中找不到很多。

    一线while循环 (One-Line while Loops)

    As with an if statement, a while loop can be specified on one line. If there are multiple statements in the block that makes up the loop body, they can be separated by semicolons (;):

    if语句一样,可以在一行上指定while循环。 如果在构成循环体的块中有多个语句,则可以用分号( ; )分隔它们:

    >>>
    >>> n = 5
    >>> while n > 0: n -= 1; print(n)
    
    4
    3
    2
    1
    0
    
    
    >>>

    This only works with simple statements though. You can’t combine two compound statements into one line. Thus, you can specify a while loop all on one line as above, and you write an if statement on one line:

    但是,这仅适用于简单的语句。 您不能将两个复合语句合并为一行。 因此,您可以如上所述在一行上全部指定一个while循环,然后在一行上编写一个if语句:

    >>>
    >>> if True: print('foo')
    
    foo
    
    
    >>>

    But you can’t do this:

    但是您不能这样做:

    >>>
    >>> while n > 0: n -= 1; if True: print('foo')
    SyntaxError: invalid syntax
    
    
    >>>

    Remember that PEP 8 discourages multiple statements on one line. So you probably shouldn’t be doing any of this very often anyhow.

    请记住, PEP 8不鼓励在一行上使用多个语句。 因此,您可能不应该经常这样做。

    结论 (Conclusion)

    In this tutorial, you learned about indefinite iteration using the Python while loop. You’re now able to:

    在本教程中,您学习了使用Python while循环进行无限迭代的方法。 您现在可以:

    • Construct basic and complex while loops
    • Interrupt loop execution with break and continue
    • Use the else clause with a while loop
    • Deal with infinite loops
    • 构造基本而复杂的while循环
    • 中断循环执行并breakcontinue
    • else子句与while循环一起使用
    • 处理无限循环

    You should now have a good grasp of how to execute a piece of code repetitively.

    现在,您应该掌握如何重复执行一段代码。

    The next tutorial in this series covers definite iteration with for loops—recurrent execution where the number of repetitions is specified explicitly.

    本系列的下一篇教程将介绍带for循环的确定迭代 -循环执行,其中明确指定重复次数。

    翻译自: https://www.pybloggers.com/2018/11/python-while-loops-indefinite-iteration/

    展开全文
  • 由以下while构成循环循环体执行的次数是( )。  int k=0;  while ( k= -1 ) k++; A)无限次 B)一次也不执行 C)执行一次 D)有语法错,不能执行
  • While(true)无限循环

    万次阅读 2017-10-08 19:04:08
    编写应用程序,输出满足1+2+3…+n的最大正整数n。 public class Xiti3_6 { public static void main(String args[]) { int n=1; long sum=0; while(tr

    编写应用程序,输出满足1+2+3…+n<8888的最大正整数n。


    public class Xiti3_6
    {
    public static void main(String args[])
    {
    int n=1;
    long sum=0;
    while(true) //无限循环
    {
    sum=sum+n;
    n++;
    if(sum>=8888)
    break; //停止
    }
    System.out.println(“满足条件的最大整数:”+(n-1));
    }
    }

    while(true)作为无限循环,经常在不知道循环次数的时候使用,并且需要在循环内使用break才会停止。

    在JAVA中while(true)不等价于while(1),因为JAVA强制要求while()里面的条件表达式必须是boolean型,而不能是int。但是在C/C++中两者等价。

    展开全文
  • 通过while实现程序的无限循环

    千次阅读 2014-08-05 22:54:45
    public class WhileTest { public static void main(String[] args) { Scanner sc =new Scanner(System.in); while(true) { System.out.println("欢迎光临,1.继续循环 0.结束循环"); int flag = sc....

    实现的效果:



    代码如下:

    package pm;
    
    import java.util.Scanner;
    
    public class WhileTest {
    	public static void main(String[] args) {
    		Scanner sc =new Scanner(System.in);
    		while(true)
    		{
    			System.out.println("欢迎光临,1.继续循环 0.结束循环");
    			int flag = sc.nextInt();
    			if(flag!=1)
    			{
    				break;
    			}
    		}
    		System.out.println("程序结束");
    	}
    }
    


    展开全文
  • 无限循环while(1)和for(;;)区别

    千次阅读 2020-07-30 01:07:10
    无限循环while(1)和for(;;)区别1.1 结论:性能相同1.2 验证1.2.1 编写两个文件for.c和while.c1.2.2 生成汇编文件for.s和while.s1.2.3 对比汇编文件1.2.4 gcc版本 1. 无限循环while(1)和for(;;)区别 1.1 结论:性能...

    1. 无限循环while(1)和for(;;)区别

    1.1 结论:性能相同

    • for(;;),这两个;;空语句,编译器一般会优化掉的,直接进入死循环。

    • while(1),每循环一次都要判断常量1是不是等于零,在这里while比for多做了这点事。

    • gcc version 9.3.0 (GCC),从汇编的角度来说,都会优化掉的

    1.2 验证

    1.2.1 编写两个文件for.c和while.c

    // filename: for.c
    int main(int argc, char const *argv[])
    {
        for(;;)
        {}
    
        return 0;
    }
    
    // filename: while.c
    int main(int argc, char const *argv[])
    {
        while(1)
        {}
    
        return 0;
    }
    

    1.2.2 生成汇编文件for.s和while.s

    gcc -S -o for.s for.c
    gcc -S -o while.s while.c
    

    1.2.3 对比汇编文件

    除了文件名不同,其余都相同。

    ; filename: for.s
    	.file	"for.c"
    	.text
    	.globl	main
    	.type	main, @function
    main:
    .LFB0:
    	.cfi_startproc
    	pushq	%rbp
    	.cfi_def_cfa_offset 16
    	.cfi_offset 6, -16
    	movq	%rsp, %rbp
    	.cfi_def_cfa_register 6
    	movl	%edi, -4(%rbp)
    	movq	%rsi, -16(%rbp)
    .L2:
    	jmp	.L2
    	.cfi_endproc
    .LFE0:
    	.size	main, .-main
    	.ident	"GCC: (GNU) 9.3.0"
    	.section	.note.GNU-stack,"",@progbits
    
    
    ; filename: whiles
    	.file	"while.c"
    	.text
    	.globl	main
    	.type	main, @function
    main:
    .LFB0:
    	.cfi_startproc
    	pushq	%rbp
    	.cfi_def_cfa_offset 16
    	.cfi_offset 6, -16
    	movq	%rsp, %rbp
    	.cfi_def_cfa_register 6
    	movl	%edi, -4(%rbp)
    	movq	%rsi, -16(%rbp)
    .L2:
    	jmp	.L2
    	.cfi_endproc
    .LFE0:
    	.size	main, .-main
    	.ident	"GCC: (GNU) 9.3.0"
    	.section	.note.GNU-stack,"",@progbits
    
    

    1.2.4 gcc版本

    $ gcc -v
    Using built-in specs.
    COLLECT_GCC=gcc
    COLLECT_LTO_WRAPPER=/usr/local/libexec/gcc/x86_64-pc-linux-gnu/9.3.0/lto-wrapper
    Target: x86_64-pc-linux-gnu
    Configured with: ../gcc-9.3.0/configure --enable-checking=release --enable-languages=c,c++ --disable-multilib
    Thread model: posix
    gcc version 9.3.0 (GCC)
    
    展开全文
  • Python程序控制结构(二)循环结构:
  • While循环结构

    2020-09-08 22:15:32
    1.while循环语句 1.1循环概念 循环是程序设计语言中反复执行某些代码的一种计算机处理过程 1.2 while循环的作用 重复执行某些代码 1.3 while循环的基本语法 while 条件: ____反复执行的代码 …… whilewhile...
  • #include<stdio.h> int main(void) { int i = 1; while(1) { if(i--) { printf("%d ", i); } } return 0; }
  • 无限循环有两种常用的方法: while(1) 和 for(; ; ) 。 两种方法的效果一样,相比之下,哪种更好些? 编译后代码对比: 1、while( 1 ); 00401028 mov eax,10040102D test eax,eax0040102F je main+23h ...
  • while循环 ...循环条件一直为TRUE就会造成无限循环(死循环),我们正常的业务编程中应该尽量避免死循环,会影响程序性能或者造成程序卡死崩溃! problem 输出1~100: 代码如下: public static v
  • 判断分数是否为无限循环小数

    万次阅读 2018-06-12 22:42:12
    之前做编程题,有一个部分需要判断一个分数是否为无限循环小数,挺有意思,特此整理记录如下: 问题描述(大概意思是) 已知分子a和分母b ,判断 分数a/b是否为无限循环小数 1.已知结论 将分数化为最简...
  • 这里写自定义目录标题C语言中,在学习do while循环结构的时候可能会遇到的问题关于do while代码加注释解释功能 C语言中,在学习do while循环结构的时候可能会遇到的问题 hi,你好,这是小编在第一次学习c语言的do ...
  • C++入门基础知识——循环、嵌套循环、无限循环C++入门基础知识[3]——循环、嵌套循环、无限循环5、循环语句5.1 循环类型5.2 while循环5.3 for循环5.4 do...while循环5.5 三个循环关系6、嵌套循环6.1 嵌套 for 循环...
  • 循环控制语句goto语句和if语句构成循环while语句do...while语句for语句 goto语句和if语句构成循环 goto语句的一般形式: 形式一 形式二 goto 语句标号—— – ````````````````````````… … |– ...
  • 如果你喜欢的人要你说一万遍“亲爱的,我爱你一万年!” ,怎么办? 像这样打一万次吗? System.out.println(“说第1遍:亲爱的,我爱你一万年!...使用while循环 int i = 1; while ( i <= 100 ){ System.o
  • 知识点:简单循环WHILE 循环,数值型 FOR 循环,CONTINUE 语句以及嵌套循环等。PL/SQL 有四种类型的循环:简单循环WHILE 循环、FOR 循环以 及游标 FOR 循环。本章会讨论前三种循环,并学习 Oracle 11g 中所引入...
  • 巧用while(true){ }死循环的一个小例子

    万次阅读 2017-06-21 22:56:30
    //巧用while(true){}死循环 System . out . println ( "请输入一个1-5的整数:" ) ; int num = sc . nextInt ( ) ; switch ( num ) { case 1 : System . out . println ( "新建" )...
  • 7.1 while循环

    2020-07-07 14:52:12
    while循环的通用形式如下: while ( expression ) statement statement部分可以是以分号结尾的简单语句,也可以是用花括号括起来的复合语句。 到目前为止,程序示例中的expression部分都使用关系表达式。也...
  • while循环

    2017-10-31 09:14:11
    在Python中,while循环就是所谓的“条件控制的”循环,因为循环的任务会一直执行直到达到期望的条件。一旦达到条件,循环就停止了。例如,你可能想要循环的任务会一直执行,直到某个条件不再为真。在这种情况下,...
  • 文章目录while语句注意:do......while语句比较while与do-while语句【示例:猜数字】 这节课我们来学习新的控制结构——循环结构。那么我们已经学会使用顺序结构来让机器按部就班的解决问题;也学会了使用选择结构来...
  • Python之if判断语句与while和for循环

    千次阅读 多人点赞 2017-03-08 22:30:12
    Python之if判断语句与while和for循环 Python之if判断语句与while和for循环 5-1 Python之if语句 5-2 Python之 if-else 5-3 Python之 if-elif-else 5-4 Python之 for循环 5-5 Python之 while循环 5-6 Python之 break...
  • 一、for语句 for(初始化语句; 循环判断语句; 循环后的操作表达式){ 循环体;... 无限循环: for(;;){} while(true){} for循环的初始化表达式和判断条件以及控制循环语句能否有多条? 可以 for(int i...
  • 一、概述 循环:就是在满足一定条件的时候,...二、用goto语句构成循环。 #include <stdio.h> int main() { int i=1; L1:printf("%d,",i); i=i+1; goto L1; return 0; } 程序中反复执行的部分就称为循环体 这
  • 测试开发笔记

    万次阅读 多人点赞 2019-11-14 17:11:58
    48 七、补充提高 49 第六章 C语言 49 C语言中的存储 50 数据类型 50 常量 53 结构体 54 条件/分支逻辑 54 Switch 54 If 55 循环 55 For 55 while 56 do…while 56 函数 56 第七章 Windows环境搭建 59 一、名词注解...
  • while结构

    2021-09-10 15:56:34
    while循环 do...while循环 for 循环 在java5中引入了一种主要用于数组的增强循环型for循环。 1.while循环 while时最基本的循环,它的结构为: While (循环条件){ 循环体(语句); 循环...
  • 在R语言中,可以使用for、while 以及repeat-break实现循环语句。循环语句可以简单依据计数操作(当计数器达到了设定的循环次数时自动停止)或者某一向量来进行轮询。 1.for循环语句 一组用户在网上的页面浏览...
  • 对于一个分数(不一定是最简形式),给出它的小树形式,如果小数有循环节的话,把循环节放在一对圆括号中. 例如,1/4 =0.25,1/3=0.3333写成0.(3),1/7= 0.142857142857...写成0.(142857)。如果结果是一种整数xxx,则...
  • 目录引言while语句案例while...else循环语句避免死循环问题for语句案例通过序列索引迭代for...else循环语句案例循环控制语句(break、continue、pass)break语句continue语句二级标题三级标题四级标题五级标题六级...
  • 循环的几种: 1.计数循环:执行次数...3.无限循环:一旦启动就一直执行下去。 4.迭代器循环:对容器类里面的每个元素执行一次操作。 好习惯: 1.减少能影响该循环各种因素的数量。 2.把循环内部当做一个子程序看...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 15,409
精华内容 6,163
关键字:

while构成无限循环