6번

문제

두 자연수 A와 B가 주어진다. 이때, A+B, A-B, A*B, A/B(몫), A% B(나머지)를 출력하는 프로그램을 작성하시오.

 

입력

두 자연수 A와 B가 주어진다. (1 ≤ A, B ≤ 10,000)

 

출력

첫째 줄에 A+B, 둘째 줄에 A-B, 셋째 줄에 A*B, 넷째 줄에 A/B, 다섯째 줄에 A%B를 출력한다.

 

C++

#include <iostream>
using namespace std;
int main(){
    int a,b;
    cin >> a;
    cin >> b;
    cout << a+b << endl;
    cout << a-b << endl;
    cout << a*b << endl;
    cout << a/b << endl;
    cout << a%b << endl;
    
    return 0;
}

 

줄바꾸기 endl 사용

 

C#

using System;
class Program{
    static void Main(string[] args){
        string input = Console.ReadLine();
        string[] arr_input = input.Split(' ');
        int a = int.Parse(arr_input[0]);
        int b = int.Parse(arr_input[1]);
        Console.WriteLine(a+b);
        Console.WriteLine(a-b);
        Console.WriteLine(a*b);
        Console.WriteLine(a/b);
        Console.WriteLine(a%b);
    }
}

 

ReadLine으로 입력을 한 줄로 받고 string.Split을 사용해서 공백으로 두 값을 구분하여 사용한다.

 

Python

str = input()
arr = str.split(' ')
a = int(arr[0])
b = int(arr[1])
print(a+b, a-b, a*b, a//b, a%b, sep='\n')

 

파이썬의 경우 '/' , '//' 연산자가 존재한다.

앞의 두 언어들은 연산하는 두 값이 모두 int 타입이기 때문에 / 연산자를 사용하여 계산하게 되면 결과도 정수형으로 반환되기 때문에 소수점은 버려지게 된다. 하지만 파이썬의 경우 정수형간의 나눗셈은 float으로 반환하기 때문에 문제에서 몫만을 출력해야 하고 이를 위해서는 몫을 구하는 연산자 '//'를 사용해야 한다.

 

728x90
반응형

+ Recent posts