Menu
CoddyTech

정수와 소수 계산

Coddy의 Swift 개발자를 위한 C# 코스 레슨. 48개 중 4번째.

Swift의 Int 나눗셈과 C#의 int 나눗셈은 0을 향해 버림합니다. 소수점이 있는 결과를 얻으려면 나누기 전에 형 변환하세요. Swift Foundation의 Decimal과 C#의 decimal은 서로 다른 API를 사용하는 서로 다른 형식입니다. Swift의 Double 계산이 자동으로 decimal 산술이 된다고 가정하지 마세요.

두 int를 나누면 0을 향해 버림합니다. 소수점이 있는 결과가 필요하면 나누기 전에 피연산자 하나를 double로 변환하세요. Decimal은 decimal 산술을 사용하며 m 리터럴 접미사가 있습니다. 이는 나중에 금액을 계산할 때 유용합니다. int나 double 매개변수 모두 임의 정밀도 정수로 묵시적으로 변환되지 않습니다.

Swift 참조

import Foundation

print(5/2)
print(Double(5)/2)

Main 안의 C# 문장

Console.WriteLine((5 / 2).ToString());
Console.WriteLine(((double)5 / 2).ToString("0.0", CultureInfo.InvariantCulture));

이 내용은 특정 개념을 집중적으로 가르치기 위한 발췌문입니다. 챌린지 파일에는 완전한 실행 래퍼가 포함되어 있으며, 위 코드 조각은 관련 선언과 문장만 보여 줍니다.

참조 출력:

2
2.5

C# 출력:

2
2.5
challenge icon

챌린지

쉬움

입력 줄에는 정수 total과 count가 포함됩니다. 두 값의 부동소수점 몫을 반환하고, count가 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 = I(input[0]); string before0=Snapshot(a0);
var a1 = I(input[1]); string before1=Snapshot(a1);

var result = Exercise.Solve(a0,a1);
if (Snapshot(a0) != before0) throw new Exception("Input mutation");
if (Snapshot(a1) != before1) throw new Exception("Input mutation");
Console.WriteLine(result.ToString("0.00", CultureInfo.InvariantCulture));
}
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

Swift 개발자를 위한 C#의 모든 레슨

직접 연습해 보세요: 온라인 C# 컴파일러