zoukankan      html  css  js  c++  java
  • While 循环

    实例

    While 循环
    利用 while 循环在指定条件为 true 时来循环执行代码。
    Do while 循环
    利用 do...while 循环在指定条件为 true 时来循环执行代码。在即使条件为 false 时,这种循环也会至少执行一次。这是因为在条件被验证前,这个语句就会执行。

    语法: 

    while (变量<=结束值)
    {
        需执行的代码
    }

    解释:下面的例子定义了一个循环程序,这个循环程序的参数 i 的起始值为 0。该程序会反复运行,直到 i 大于 10 为止。i 的步进值为 1

    <html>
    <body>
    <script type="text/javascript">
    var i=0
    while (i<=10)
    {
    document.write("The number is " + i)
    document.write("<br />")
    i=i+1
    }
    </script>
    </body>
    </html>

    输出结果为:

    The number is 0
    The number is 1
    The number is 2
    The number is 3
    The number is 4
    The number is 5
    The number is 6
    The number is 7
    The number is 8
    The number is 9
    The number is 10

    do...while 循环

    do...while 循环是 while 循环的变种。该循环程序在初次运行时会首先执行一遍其中的代码,然后当指定的条件为 true 时,它会继续这个循环。所以可以这么说,do...while 循环为执行至少一遍其中的代码,即使条件为 false,因为其中的代码执行后才会进行条件验证。

    语法:

    do
    {
        需执行的代码
    }
    while (变量<=结束值)

    实例:

    <html>
    <body>
    <script type="text/javascript">
    var i=0
    do 
    {
    document.write("The number is " + i)
    document.write("<br />")
    i=i+1
    }
    while (i<0)
    </script>
    </body>
    </html>

     输出结果:

    The number is 0

     

    不能一味纸上谈兵所以下面有一个小例子可以帮助熟悉和巩固while循环!

    第一个从键盘输出小明的成绩

    当成绩为100时,奖励一辆宝马汽车!

    当成绩为[80-99]时,奖励一台iphone!

    当成绩为[60-80]时,奖励一本参考书!

    其他分数时,什么奖励也没有!然后利用将出入错误的值让用户从新输入。

    <script type="text/javascript">
            while(true){
                var cj = prompt("输入小明的成绩");
                if(cj < 100 && cj > 0){
                    break
                }
                alert("请重新输入有效成绩")
            }
            function talbe(cj){
                if(isNaN(cj) || cj == 0){
                    document.write("输出错误")}
                else if(cj == 100){
                    alert("奖励一台宝马")
                }
                else if(cj >= 80 && cj <= 99){
                    alert("奖励一台iphone")
                }
                else if(cj >= 60 && cj < 80){
                    alert("奖励一本参考书")
                }
                else if(cj < 60){
                    alert("打一顿")
                    }
                else(
                    alert("拉出去毙了")
                )
            }
            talbe(cj)
        </script>

    页面效果:

  • 相关阅读:
    android学习笔记----启动模式与任务栈(Task)
    二叉搜索树转化成双向链表
    复杂链表的复制
    判断是否为二叉搜索树的后序遍历序列
    树的子结构
    调整数组顺序使奇数位于偶数前面,且奇数之间、偶数之间的相对位置不变
    android学习笔记----HandlerThread学习
    android学习笔记----Handler的使用、内存泄漏、源码分析等一系列问题
    原因分析——cin,coutTLE,scanf,printf就AC
    洛谷P1618_三连击(升级版)
  • 原文地址:https://www.cnblogs.com/niuyaomin/p/11815812.html
Copyright © 2011-2022 走看看