Menu
CoddyTech

정수와 소수 계산

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

C와 C#은 모두 int 나눗셈에서 0을 향해 버림하며, 분수 부분을 유지하려면 나눗셈 전에 형 변환을 해야 합니다. C에서 (double)5 / 2가 작동하는 방식과 같습니다. 차이는 예외적인 경우에 있습니다. C에서 0으로 정수 나눗셈을 하면 정의되지 않은 동작이 발생하지만, C#에서는 DivideByZeroException이 발생합니다. 또한 C#에는 m 리터럴을 사용하는 내장 128비트 decimal 형식이 있지만 표준 C17에는 없습니다. 금액을 다룰 때는 숫자 모델을 신중하게 선택하세요.

두 int를 나누면 0을 향해 버림합니다. 분수 결과가 필요하면 나눗셈 전에 피연산자 하나를 double로 변환하세요. Decimal은 decimal 연산과 m 리터럴 접미사를 사용하므로 이후의 금액 계산에 유용합니다. int나 double 매개변수는 어느 쪽도 임의 정밀도 정수로 암묵적으로 변환되지 않습니다.

C 참고 코드

#include <stdio.h>

int main(void) {
    printf("%d\n", 5 / 2);
    printf("%.1f\n", (double)5 / 2);
    return 0;
}

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실력 점검

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

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

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