인덱스를 사용하는 for 반복문
Coddy의 GDScript 개발자를 위한 C# 코스 레슨. 48개 중 14번째.
GDScript에서는 for i in range(3) 또는 간단히 for i in 3이라고 작성하며, C 스타일의 for문은 없습니다. C#의 for문에서는 초기화, 비교, 업데이트를 직접 지정합니다. 추가 반복이 발생하지 않도록 Length에 도달하기 전에 멈춥니다. GDScript와 마찬가지로 C#의 반복 변수는 반복문 안에서만 존재하며, 반복문이 끝난 뒤에는 읽을 수 없습니다.
for문은 초기화, 불리언 조건, 업데이트를 결합합니다. 범위를 벗어나지 않도록 Length와 엄격한 미만 비교를 사용합니다. 반복 변수는 선언된 범위 안에서만 존재합니다. 반복문 전에 선언한 변수에 값을 누적합니다.
GDScript 참고 코드
extends Node
func _ready() -> void:
var total := 0
for i in range(3):
total += i
print(total)Main 내부의 C# 문장
int total = 0;
for (int i = 0; i < 3; i++) total += i;
Console.WriteLine(total);GDScript 참고 코드는 완전한 스크립트입니다. C# 코드 조각은 학습에 필요한 부분만 보여 줍니다. 과제 파일에는 실행 가능한 전체 래퍼가 포함되어 있으며, 위 코드 조각에는 관련 선언과 문장이 나와 있습니다.
참고 출력:
3C# 출력:
3챌린지
쉬움쉼표로 구분된 정수 배열의 각 항목에 대해 인덱스 * 값의 가중치 합을 반환하세요. 인덱스는 0부터 시작합니다. 입력이 비어 있으면 0을 반환합니다.
잠금 해제된 C# 파일을 수정하세요. 잠긴 상태로 표시된 Main.cs는 설명된 줄을 읽고, Exercise.Solve를 호출하고, 입력이 변경되지 않았는지 확인한 뒤 마지막에 줄 바꿈 하나를 포함해 결과를 출력합니다. 선언된 API를 유지하세요. 두 번째 Main을 추가하거나 진단 출력을 출력하지 마세요.
직접 해보기
using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
public class Program {
static int I(string text) { return int.Parse(text,CultureInfo.InvariantCulture); }
static int[] Ints(string text) { return text.Length==0 ? new int[0] : text.Split(',').Select(I).ToArray(); }
static string[] Words(string text) { return text.Length==0 ? new string[0] : text.Split(','); }
static string Snapshot(object value) { if (value==null) return "<null>"; if (value is string) return (string)value; var sequence=value as System.Collections.IEnumerable; if (sequence!=null) { var items=new List<string>(); foreach (object item in sequence) items.Add(Snapshot(item)); return string.Join("|",items); } return Convert.ToString(value,CultureInfo.InvariantCulture); }
public static void Main() {
System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
var rows = new List<string>(); string line; while ((line=Console.ReadLine()) != null) rows.Add(line);
string[] input=rows.ToArray();
var a0 = Ints(input[0]); string before0=Snapshot(a0);
var result = Exercise.Solve(a0);
if (Snapshot(a0) != before0) throw new Exception("Input mutation");
Console.WriteLine(result);
}
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
GDScript 개발자를 위한 C#의 모든 레슨
1여기서 시작하기
첫 번째 C# 프로그램 실행하기직접 연습해 보세요: 온라인 C# 컴파일러