Menu
CoddyTech

정수와 소수 계산

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

C++와 C#의 int 나눗셈은 0을 향해 버림하며, 소수 부분을 유지하려면 나눗셈 전에 형 변환을 해야 합니다. C#에는 m 리터럴을 사용하는 decimal 형식도 내장되어 있지만, 표준 C++에는 이에 직접 대응하는 decimal 기본 형식이 없습니다. 금액을 다룰 때는 숫자 형식 선택이 중요합니다.

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

C++ 참조

#include <algorithm>
#include <array>
#include <cctype>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <memory>
#include <optional>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
using namespace std;

int main() {
cout << 5 / 2 << "\n";
cout << fixed << setprecision(1) << static_cast<double>(5) / 2 << "\n";
}

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# 컴파일러