for문과 조기 종료
Coddy의 C# 개발자를 위한 Go 코스 레슨. 48개 중 10번째.
C#은 while과 do/while을 서로 다른 구문으로 제공합니다. Go는 횟수가 정해진 루프와 조건만 사용하는 루프 모두에 for를 사용합니다. 헤더에서 선언한 변수의 범위는 해당 루프에 한정되며, 본문은 항상 중괄호로 묶습니다.
for는 Go의 반복 키워드입니다. 초기화/조건/갱신을 모두 사용하거나, 조건만 사용하거나, 절을 하나도 사용하지 않을 수 있습니다. break는 가장 가까운 루프를 종료하고, continue는 다음 반복으로 넘어갑니다. 루프 헤더에서 선언한 변수는 해당 루프 안에서만 사용할 수 있습니다.
C# 예제
using System;
using System.Collections.Generic;
using System.Linq;
class Program { static void Main() {
int n=8; while(n>1){n/=2;}Console.WriteLine(n);
} }출력 결과:
1Go 예제
package main
import ("fmt")
func main(){n:=8
for n>1 { n/=2 }
fmt.Println(n)}
Go 출력 결과:
1챌린지
쉬움0 <= n <= 100일 때, 1부터 n까지의 정수의 합을 반환하세요.
선언된 API를 구현하고, 출력하지 말고 결과를 반환하세요. 드라이버는 필요한 API를 확인하고 호출자의 입력을 보존합니다. 컬렉션의 stdout 출력은 JSON이 아닌 Go의 대괄호 형식을 사용합니다.
코드는 exercise.go에 작성하세요. main.go에는 제공된 입력/출력 코드가 있으며 수정할 수 없습니다. 하나의 평평한 package main을 유지하고 두 번째 main을 추가하지 마세요.
직접 해보기
package main
import ("fmt";"strings";"strconv";"bufio";"os")
var input []string
func L(i int)string{if i<len(input){return input[i]};return ""}
func I(i int)int{n,e:=strconv.Atoi(L(i));if e!=nil{panic(e)};return n}
func Ints(i int)[]int{out:=[]int{};if L(i)==""{return out};for _,s:=range strings.Split(L(i),","){n,e:=strconv.Atoi(s);if e!=nil{panic(e)};out=append(out,n)};return out}
func Words(i int)[]string{if L(i)==""{return []string{}};return strings.Split(L(i),",")}
func must(ok bool,message string){if !ok{panic("API: "+message)}}
func main(){
scanner:=bufio.NewScanner(os.Stdin);for scanner.Scan(){input=append(input,scanner.Text())};if scanner.Err()!=nil{panic(scanner.Err())}
a0:=I(0); before0:=fmt.Sprint(a0)
result:=Solve(a0)
must(fmt.Sprint(a0)==before0,"input mutation")
fmt.Println(result)
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
C# 개발자를 위한 Go의 모든 레슨
직접 연습해 보세요: 온라인 Go 컴파일러