×
Go 语言教程Go 语言环境安装Go 语言结构Go 语言基础语法Go 语言数据类型Go 语言变量Go 语言常量Go 语言运算符Go 语言条件语句Go 语言循环语句Go 语言函数Go 语言变量作用域Go 语言数组Go 语言指针Go 语言结构体Go 语言切片(Slice)Go 语言范围(Range)Go 语言Map(集合)Go 语言递归函数Go 语言类型转换Go 语言接口Go 错误处理Go 语言开发工具

Go 语言循环嵌套


Go 语言循环语句Go 语言循环语句


Go 语言允许用户在循环内使用循环。接下来我们将为大家介绍嵌套循环的使用。

语法

以下为 Go 语言嵌套循环的格式:

for [condition |  ( init; condition; increment ) | Range]
{
   for [condition |  ( init; condition; increment ) | Range]
   {
      statement(s);
   }
   statement(s);
}

实例

以下实例使用循环嵌套来输出 2 到 100 间的素数:

package main

import "fmt"

func main() {
   /* 定义局部变量 */
   var i, j int

   for i=2; i < 100; i++ {
      for j=2; j <= (i/j); j++ {
         if(i%j==0) {
            break; // 如果发现因子,则不是素数
         }
      }
      if(j > (i/j)) {
         fmt.Printf("%d  是素数\n", i);
      }
   }  
}

以上实例运行输出结果为:

2  是素数
3  是素数
5  是素数
7  是素数
11  是素数
13  是素数
17  是素数
19  是素数
23  是素数
29  是素数
31  是素数
37  是素数
41  是素数
43  是素数
47  是素数
53  是素数
59  是素数
61  是素数
67  是素数
71  是素数
73  是素数
79  是素数
83  是素数
89  是素数
97  是素数

Go 语言循环语句Go 语言循环语句


分类导航

关注微信下载离线手册

bootwiki移动版 bootwiki
(群号:472910771)