1 / 10

For…Next 循环

计算机科学系 郭阳勇. For…Next 循环. For…Next 格式. For. 循环变量 = 初值. To. 终值. [Step= 步长 ]. 循环体. [ 条件语句系列 Exit For 结束条件语句系列 ]. Next [ 循环变量 ]. 例 1 用 For 循环计算 1 到 100 自然数之和. 分析:先确定循环变量,这里定义为 i ,其范围为 1 到 100 ;然后确定步长为 1 ;最后确定循环变量 i 之和存放变量 s( 初始值为 0). For. i = 1. To. 100. Step = 1. s = s + i.

Download Presentation

For…Next 循环

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 计算机科学系 郭阳勇 For…Next循环

  2. For…Next格式 For 循环变量=初值 To 终值 [Step=步长] 循环体 [条件语句系列 Exit For 结束条件语句系列] Next [循环变量]

  3. 例1 用For循环计算1到100自然数之和 分析:先确定循环变量,这里定义为i,其范围为1到100;然后确定步长为1;最后确定循环变量i之和存放变量s(初始值为0) For i =1 To 100 Step =1 s = s + i Next i 问题:Step = 1可以省略吗?Next i中的变量i可以省略吗?

  4. 例2 用For循环计算1到100自然数之和(省略步长及Next i中的循环变量) 可以省略Step=1 可以省略Next i的i For i =1 To 100 Step =1 s = s + i Next i Next 问题: Step=-1时怎样修改程序计算1到100的和?

  5. 例3 用For循环计算1到100自然数之和(步长为-1) 分析:Step=-1,循环变量i的初始值为最大值100,其范围为100到1 For i =100 To 1 Step =-1 s = s + i Next i 问题:步长为小数可以吗?

  6. 例4 用For循环计算1到100能被0.5整除数之和 分析:先确定循环变量i的初始值为1,其范围为1到100;再确定其步长Step=0.5;最后循环体变量之和s = s + i For i =1 To 100 Step =0.5 s = s + i Next i 问题:循环体中途能否退出循环呢?

  7. 例5 用For循环计算1到100自然数之和,找到其和大于3000时的循环数并输出 中途可以退出For循环 For i =1 To 100 Step =1 s = s + i If s > 3000 Then Exit For End If Next i

  8. 总结 • For…Next实现基于循环变量的循环 • 必须确定循环变量的上下界取值范围 • 必须确定其步长Step,默认值为1,Step可取任意值 • 可以使用Exit For中途退出循环

  9. 练习 • 使用For循环计算-500到0的所有被5整除的数之和。 • 使用For循环计算1到100所有能被0.1整除的数之和。

  10. 谢谢!

More Related