C#/Foundation
002. 정수 2개를 입력 받아 덧셈, 뺄셈, 곱셈, 나눗셈, 나머지 값을 출력
페프
2021. 3. 16. 06:13
산술연산자를 사용하여 입력 받은 정수 두 개로 덧셈, 뺄셈, 곱셈, 나눗셈, 나머지값을 출력해보았다.
002. 정수 2개를 입력받아 덧셈, 뺄셈, 곱셈, 나눗셈, 나머지 값을 출력하시오
#include using namespace std; int main() { int num1,num2; cout << "두 개의 정수를 입력하세요 : "; cin >> num1 >> num2; cout << num1 << " + " << num2 << "= " << num1 + num2 << endl; cout << num1 << "..
ffeff45.tistory.com
위에 링크는 C++으로 같은 문제를 짜보았던 것이다.
C#에서는 산술연산자를 이용해 코드를 짜는 법이 두 가지 존재한다.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace B002
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("첫 번쨰 숫자를 입력하세요 : ");
int x = int.Parse(Console.ReadLine());
Console.WriteLine("두 번쨰 숫자를 입력하세요 : ");
int y = int.Parse(Console.ReadLine());
//방법 1
Console.WriteLine(x + " + " + y + " = " + (x + y));
Console.WriteLine(x + " - " + y + " = " + (x - y));
Console.WriteLine(x + " * " + y + " = " + (x * y));
Console.WriteLine(x + " / " + y + " = " + (x / y));
Console.WriteLine(x + " % " + y + " = " + (x % y));
//방법2
Console.WriteLine(" {0} + {1} = {2}", x, y, x + y);
Console.WriteLine(" {0} - {1} = {2}", x, y, x - y);
Console.WriteLine(" {0} * {1} = {2}", x, y, x * y);
Console.WriteLine(" {0} / {1} = {2}", x, y, x / y);
Console.WriteLine(" {0} % {1} = {2}", x, y, x % y);
}
}
}
✔ Console.WriteLine(x + " + " + y + " = " + (x + y)); 에서 (x+y)는 굉장히 중요하다. ()가 없으면 문자 = 다음에 또 x를 보여주는 식이 되어 버리기 때문이다.
✔ Console.WriteLine(" {0} + {1} = {2}", x, y, x + y) 은 {0}=x, {1}=y, {2}=x+y이다. 여기선 ","로 구분하였기에 굳이()가 필요 없다.