Menu
CoddyTech

정수와 소수 연산

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

Python은 정수 피연산자에 대해 소수 결과를 반환합니다. C#의 정수 피연산자는 먼저 형 변환하지 않으면 0을 향해 버림하여 나눗셈합니다. Python의 //는 내림하므로 음수에서는 0을 향한 버림과 다릅니다. C#의 decimal은 Python의 float와 다르므로 숫자 모델을 신중하게 선택하세요.

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

Python 참조

print(5 // 2)
print(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실력 점검

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

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

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