티스토리 뷰
[ 초보자를 위한 C# 200제 ] C#_005
using System;
using System.Windows.Forms;
namespace Project_005
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
//-------------------이곳에 초기화 -------------------//
this.Clear();
}
private void Clear()
{
this.txtNum1.Text = "";
this.txtNum2.Text = "";
this.txtResult.Text = "";
this.IbResult.Text = "Ready";
}
private void btnAdd_Click(object sender, EventArgs e)
{
try
{
// Calculator 파라미터에 사칙연산 중 어떤 연산인지 알리는 문자열 포함
this.txtResult.Text = Calculator(this.txtNum1.Text, this.txtNum2.Text, "+").ToString();
this.IbResult.Text = "+"; // 덧셈
}
catch { } // 더 이상 처리할 것이 없다.
}
private void btnMinus_Click(object sender, EventArgs e)
{
try
{
this.txtResult.Text = Calculator(this.txtNum1.Text, this.txtNum2.Text, "-").ToString();
this.IbResult.Text = "-"; // 뺄셈
}
catch { }
}
private void btnMulti_Click(object sender, EventArgs e)
{
try
{
this.txtResult.Text = Calculator(this.txtNum1.Text, this.txtNum2.Text, "x").ToString();
this.IbResult.Text = "x"; // 곱셈
}
catch { }
}
private void btnDivide_Click(object sender, EventArgs e)
{
try
{
this.txtResult.Text = Calculator(this.txtNum1.Text, this.txtNum2.Text, "/").ToString();
this.IbResult.Text = "/"; // 나눗셈
}
catch { }
}
private void btnClear_Click(object sender, EventArgs e)
{
this.Clear(); // 청소
}
// string opp 사칙연산 중 어떤 연산인지 알리는 문자열 포함
// 두 숫자 타입 문자열을 받아서 double 숫자로 형변화하고 opp 연산 조건에 따라 사칙연산을 하고 리턴한다.
private double Calculator(string sx, string sy, string opp)
{
if (string.IsNullOrEmpty(sx) || string.IsNullOrEmpty(sy))
{
MessageBox.Show("공백이 입력되었습니다. 다시 입력하세요.");
this.Clear();
throw new Exception("공백이 입력되었습니다. 다시 입력하세요. ");
}
try
{
double x = double.Parse(sx.Trim());
double y = double.Parse(sy.Trim());
double z = 0.0; // 사칙연산 결과를 저장할 임시 변수
// 사칙연산이 어떤 것인지 판단
// switch case는 opp 문자열이 무엇인가에 따라
// z에 두 수를 더하거나 빼는 등을 한 다음 break에서 switch를 빠져나온다.
switch(opp)
{
case "+": z = x + y; break;
case "-": z = x - y; break;
case "x": z = x * y; break;
case "/": z = x / y; break;
}
return z; // 연산 결과를 저장하고 있는 z를 리턴한다.
}
catch
{
MessageBox.Show("숫자를 입력하세요. 다시 입력하세요. ");
this.Clear();
throw new Exception("숫자를 입력하세요. 다시 입력하세요. ");
}
}
}
}
[ 결과 ]
'SW > C#' 카테고리의 다른 글
[ 초보자를 위한 C# 200제 ] C#_007 (0) | 2018.03.22 |
---|---|
[ 초보자를 위한 C# 200제 ] C#_006 (0) | 2018.03.21 |
[ 초보자를 위한 C# 200제 ] C#_004 (0) | 2018.03.21 |
[ 초보자를 위한 C# 200제 ] C#_003 (0) | 2018.03.20 |
[ 초보자를 위한 C# 200제 ] C#_002 (0) | 2018.03.19 |
- Total
- Today
- Yesterday
- 오버플로우
- c
- 초보
- 영화
- 컴퓨터과학이 여는 세계
- 두 수 입력
- 튜링
- 컴퓨터과학
- 뇌를 자극하는 C# 5.0 프로그래밍
- 독서
- 정수
- 앨런 튜링
- 계산기
- 나눗셈
- 이광근
- 동적
- 초보자를 위한 C# 200제
- 유니티 기초
- 컴퓨터의 시초
- 비전공자
- 기계적 추론
- 수리 명제 자동판결 문제
- c#
- 프로그래밍
- 서울대
- 기본개념
- 프로그램
- 메서드
- dynamic
- 에니그마
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |