코딩 테스트/백준

백준 [단계별로 풀어보기 - 입출력과 사칙연산]

devrabbit22 2025. 3. 5. 00:27

2557 문자출력 문제

백준 2557

단순히 문자를 출력하는 내용으로 C++,C#을 사용해 문제를 풀기에 각 언어마다 출력문을 다르게 작성한다.

#include <iostream>

int main()
{
	std::cout << "Hello World!";
	return 0;
}

C++

using System;
class HelloWorld
{
    static void Main(string[] args)
    {
        Console.WriteLine("Hello World!");
    }
}

C#

1000 사칙연산 A+B

백준 1000

두 수를 입력받아 계산 결과를 출력하는 기초 문제이다.

두개의 int형 변수에 사용자가 입력한 값을 받고 결과로 입력받은 값의 합을 출력하는 코드를 작성한다.

#include <iostream>

int main()
{
	int A, B;
	std::cin >> A;
	std::cin >> B;

	std::cout << A + B;
	return 0;
}

C++

C#에서는 주의할 점이 있다. ReadLine을 통해 입력을 받으면  string 형태를 받는 것이 일반적인데 입력받은 값들을 int형으로 변환을 해줘야한다.

방법은 두 가지 방법을 사용해서 풀었다. 

공백을 기준으로 나눠 각 변수의 값을 배열에 할당하고 Parse 또는 Convert를 사용해 int형으로 변환한다.

  • Parse
using System;
using System.Collections.Generic;
using System.IO;

class Program
{
    static void Main(String[] args)
    {
        int A, B;

        string inputData = Console.ReadLine();
        string[] inputDatas = inputData.Split(' ');

        A = int.Parse(inputDatas[0]);
        B = int.Parse(inputDatas[1]);

        Console.WriteLine(A + B);
    }
}
  • Convert
using System;
using System.Collections.Generic;
using System.IO;

class Program
{
    static void Main(String[] args)
    { 
        string inputData = Console.ReadLine();

        string[] inputDatas = inputData.Split(' ');

        int A = Convert.ToInt32(inputDatas[0]);
        int B = Convert.ToInt32(inputDatas[1]);

        Console.WriteLine(A + B);

    }
}

1001 사칙연산 A-B

백준 1001

C++은 간단하게 변수 두개를 입력받아 - 연산의 결과값을 출력하면 된다.

#include <iostream>

int main()
{
	int A, B;
	std::cin >> A;
	std::cin >> B;

	std::cout << A - B;
	return 0;
}

C++

C#의 경우 1000번과 동일하게 공백을 기준으로 나눠서 배열에 할당해주고 int로 형변환 이후 - 연산의 결과를 출력하면 된다. 변환 방법은 위와 동일하다.

using System;
using System.Collections.Generic;
using System.IO;

class Program
{
    static void Main(String[] args)
    {
        int A, B;

        string inputData = Console.ReadLine();
        string[] inputDatas = inputData.Split(' ');

        A = int.Parse(inputDatas[0]);
        B = int.Parse(inputDatas[1]);

        Console.WriteLine(A - B);
    }
}

Parse 변환

using System;
using System.Collections.Generic;
using System.IO;

class Program
{
    static void Main(String[] args)
    {
        string inputData = Console.ReadLine();

        string[] inputDatas = inputData.Split(' ');

        int A = Convert.ToInt32(inputDatas[0]);
        int B = Convert.ToInt32(inputDatas[1]);

        Console.WriteLine(A - B);
    }
}

Convert 변환

10998번 사칙연산 곱셈

백준 10998

위의 사칙연산 문제와 동일하고 연산자만 변경하면 된다.

#include <iostream>

int main()
{
	int A, B;
	std::cin >> A;
	std::cin >> B;

	std::cout << A * B;
	return 0;
}

C++

using System;
using System.Collections.Generic;
using System.IO;

class Program
{
    static void Main(String[] args)
    {
        int A, B;

        string inputData = Console.ReadLine();
        string[] inputDatas = inputData.Split(' ');

        A = int.Parse(inputDatas[0]);
        B = int.Parse(inputDatas[1]);

        Console.WriteLine(A * B);
    }
}
using System;
using System.Collections.Generic;
using System.IO;

class Program
{
    static void Main(String[] args)
    {
        string inputData = Console.ReadLine();

        string[] inputDatas = inputData.Split(' ');

        int A = Convert.ToInt32(inputDatas[0]);
        int B = Convert.ToInt32(inputDatas[1]);

        Console.WriteLine(A * B);
    }
}

C#

1008번 사칙연산 나눗셈

C++에서 위 문제를 풀때는 소수점 자리를 고정해야 한다. 위의 방법대로 그대로 연산자만 바꾸면 오답처리가 된다.

double 데이터타입이 소수점 이하 15자리까지 나타낸다고 해도 출력은 그 이하로 되기 때문이라고 한다.

그렇기 때문에 std::fixed와 std::cout.precision()를 알고 있어야한다.

std::fixed	//소수점 아래로 고정
std::cout.precision(n)	//실수 전체 자리수 중 n자리 까지 표현

std::cout.precision()는 출력할 실수 전체 자리수를 n자리로 표현 것이다. 소수점 아래로 n자리만큼 고정하는 것이 아니다.

실수 전체에 대한 자리수 표현이다보니 만약 오차범위를 넉넉하게 주려면 precision 의 파라미터를 큰 수로 넘겨주어야 한다. 즉, cout.precision(숫자)는 유효숫자 표기 명령어다. 소수점과 상관 없이 전체 자리 숫자를 고정하는 명령어이고

cout<<fixed;는 소수점 아래부터 유효숫자를 세겠다라는 명령어다.

fixed를 해제하고 싶다면 cout.unsetf() 에 ios::fixed 를 넘겨주면 된다.

따라서 C++로 작성하면 다음과 같다.

#include <iostream>

using namespace std;

int main()
{
	double a, b;
	cin >> a >> b;

	cout << fixed;
	cout.precision(9);

	cout << a / b << endl;
	return 0;
}

C#은 그대로 연산자만 변경해주면 된다.

using System;
using System.Collections.Generic;
using System.IO;

class Program
{
    static void Main(String[] args)
    {
        string inputData = Console.ReadLine();

        string[] inputDatas = inputData.Split(' ');

        double A = Convert.ToDouble(inputDatas[0]);
        double B = Convert.ToDouble(inputDatas[1]);

        Console.WriteLine(A / B);
    }
}

10869 사칙연산

C++ C#모두 위에서 작성한 그대로 연산자만 변경해서 결과값을 출력하면 된다. C++은 소수점 고정해야하는 조건도 없기 때문에 연산을 통해 값만 출력하면 된다.

#include <iostream>
using namespace std;
 
int main(int argc, char const *argv[]) {
    int a, b;
 
    cin >> a >> b;
    
    cout << a + b << "\n"; 
    cout << a - b << "\n"; 
    cout << a * b << "\n";  
    cout << a / b << "\n";  
    cout << a % b << "\n";  
    return 0;
}
  • 다음 줄로 넘어가는 개행 부분의 경우 endl 을 써도 되지만, 나중에 빠른 입출력을 요구하는 경우에는 endl 을 지양하는 것이 좋다.
  • endl의 경우 단순히 "\n" (개행)의 역할만 하는 것이 아닌 내부 버퍼까지 비우기 때문에 그렇다. flush연산이 발생해  출력 버퍼를 강제로 비우며, 입출력이 많을 때 성능이 저하될 수 있다.
using System;
using System.Collections.Generic;
using System.IO;

class Program
{
    static void Main(String[] args)
    {
        string inputData = Console.ReadLine();

        string[] inputDatas = inputData.Split(' ');

        int A = Convert.ToInt32(inputDatas[0]);
        int B = Convert.ToInt32(inputDatas[1]);

        Console.WriteLine(A + B);
        Console.WriteLine(A - B);
        Console.WriteLine(A * B);
        Console.WriteLine(A / B);
        Console.WriteLine(A % B);
    }
}

C#


Reference

cout.precision과 fixed의 Reference

https://st-lab.tistory.com/212

 

[백준] 1008번 : A/B - [C++]

www.acmicpc.net/problem/1008 1008번: A/B 두 정수 A와 B를 입력받은 다음, A/B를 출력하는 프로그램을 작성하시오. www.acmicpc.net 문제 알고리즘 [접근 방법] 이 문제는 '부동 소수점'에 대한 이해를 필요로 하

st-lab.tistory.com