티스토리 뷰

VS-02분반수업

VS02(22-04-01)

choimyeongheon 2022. 4. 8. 03:05

[1]학점계산기2

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace _021_ScoreCal
{
  public partial class Form1 : Form
  {
    TextBox[] titles;
    ComboBox[] crds;
    ComboBox[] grds;
    public Form1()
    {
      InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
      textBox1.Text = "인체의구조와기능I";
      textBox2.Text = "일반수학I";
      textBox3.Text = "설계및프로젝트기본I";
      textBox4.Text = "자료구조";
      textBox5.Text = "비주얼프로그래밍";
      textBox6.Text = "기업가정신";
      textBox7.Text = "";

      titles = new TextBox[] {
        textBox1, textBox2, textBox3,textBox4,
        textBox5, textBox6, textBox7 };
      crds = new ComboBox[] {
        crd1, crd2, crd3, crd4, crd5, crd6, crd7};
      grds = new ComboBox[] {
        grd1, grd2, grd3, grd4, grd5, grd6, grd7 };
      int[] arrCredit = { 1, 2, 3, 4, 5 };
      List<string> listGrade = new List<string> {
        "A+","A0","B+","B0","C+","C0","D+","D0","F"};

      foreach(var cb in crds)
      {
        foreach(var c in arrCredit)
          cb.Items.Add(c);
        cb.SelectedItem = 3;
      }

      foreach(var cb in grds)
      {
        foreach (var gr in listGrade)
          cb.Items.Add(gr);
      }
    }

    private void btnCalc_Click(object sender, EventArgs e)
    {
      double totalScore = 0;
      int totalCredits = 0;

      for(int i=0; i < crds.Length; i++)
      {
        if (titles[i].Text != "")
        {
          int crd
            = int.Parse(crds[i].SelectedItem.ToString());
          totalCredits += crd;
          totalScore 
            += crd * GetGrade(grds[i].SelectedItem.ToString());
        }
      }
      txtResult.Text
        = (totalScore / totalCredits).ToString("0.00");
    }

    private double GetGrade(string v)
    {      
      if (v == "A+") return 4.5;
      else if (v == "A0") return 4.0;
      else if (v == "B0") return 3.5;
      else if (v == "B0") return 3.0;
      else if (v == "C+") return 2.5;
      else if (v == "C0") return 2.0;
      else if (v == "D+") return 1.5;
      else if (v == "D0") return 1.0;
      else return 0;
    }
  }
}

과목과 학점 그리고 등급을 받아 계산하는 프로그램이다.

TextBox[] titles;
    ComboBox[] crds;
    ComboBox[] grds;

C#의 배열 선언 형식에 따라

textbox값들을 저장하는 배열 tiles와

combobox값들을 저장하는 배열 crds,grds를 선언해준다.

textBox1.Text = "인체의구조와기능I";
      textBox2.Text = "일반수학I";
      textBox3.Text = "설계및프로젝트기본I";
      textBox4.Text = "자료구조";
      textBox5.Text = "비주얼프로그래밍";
      textBox6.Text = "기업가정신";
      textBox7.Text = "";

      titles = new TextBox[] {
        textBox1, textBox2, textBox3,textBox4,
        textBox5, textBox6, textBox7 };

textbox값들의 text프로퍼티를 일일히 설정해준 뒤

위에 선언한 tiles배열을 초기화하여 값들을 받아줍니다.

crds = new ComboBox[] {
        crd1, crd2, crd3, crd4, crd5, crd6, crd7};
      grds = new ComboBox[] {
        grd1, grd2, grd3, grd4, grd5, grd6, grd7 };

마찬가지로 crds와 grds도 초기화하여 값을 받아준다.

int[] arrCredit = { 1, 2, 3, 4, 5 };
      List<string> listGrade = new List<string> {
        "A+","A0","B+","B0","C+","C0","D+","D0","F"};

      foreach(var cb in crds)
      {
        foreach(var c in arrCredit)
          cb.Items.Add(c);
        cb.SelectedItem = 3;
      }

      foreach(var cb in grds)
      {
        foreach (var gr in listGrade)
          cb.Items.Add(gr);
      }

arrcredit에 학점들을 담아줍니다.

List<string>형식의 listgrade를 선언하여 등급들을 담아줍니다.

crds의 cb번째항에 arrcredit을 전부 설정해주면서 cb번째 디폴트값을 3으로 설정해준다.

마찬가지로 grds의 cb번째 항마다 listgrade의 gr번째항의 값을 전부 넣어준다.

디폴트는 따로 설정하지 않았다.

private double GetGrade(string v)
    {      
      if (v == "A+") return 4.5;
      else if (v == "A0") return 4.0;
      else if (v == "B0") return 3.5;
      else if (v == "B0") return 3.0;
      else if (v == "C+") return 2.5;
      else if (v == "C0") return 2.0;
      else if (v == "D+") return 1.5;
      else if (v == "D0") return 1.0;
      else return 0;
    }

다음은 getgrade함수를 작성해준다.

인자 v를 받아 값에따라 double값을 리턴해준다.

private void btnCalc_Click(object sender, EventArgs e)
    {
      double totalScore = 0;
      int totalCredits = 0;

      for(int i=0; i < crds.Length; i++)
      {
        if (titles[i].Text != "")
        {
          int crd
            = int.Parse(crds[i].SelectedItem.ToString());
          totalCredits += crd;
          totalScore 
            += crd * GetGrade(grds[i].SelectedItem.ToString());
        }
      }
      txtResult.Text
        = (totalScore / totalCredits).ToString("0.00");
    }

totalscore와 totalcredit을 선언해준다.

crds의 배열길이만큼 루프를 돌리면서 

title(과목명)이 빈칸이 아닐경우 지역변수 crd를 새로 선언해준 뒤

crds[i]번째 항의 값을 string으로 받아 저장해준다.

==========crd는 [i]번째 과목의 이수학점이다.============

그 후 totalcredit에 값을 더해준다.

==========totalcredit은 총 이수학점이다.=============

그 후 totalscore에 crd*(i번째 과목의 등급을 string으로 받아 함수를 돌려 double형태로 변환한 값)을

더해준다.

루프를 전부 돌리면totalscore와 totalcredit이 계산되었을 것이다.

이 후 txtresult의 text값을 (받은학점의 총합 / 총 이수학점)을 계산한 값을 소수 둘째자리까지 계산하여 string의 형태로 출력해준다.

마지막 textbox7은 빈칸이므로 루프에 포함되지 않았다.


[2]타이머

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace _022_timer
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
      label1.Font = new Font("맑은 고딕", 30, FontStyle.Bold);
      label1.ForeColor = Color.Blue;
    }

    private void Form1_Load(object sender, EventArgs e)
    {
      label1.Text = "";
      timer1.Interval = 1000;
      timer1.Tick += Timer1_Tick; // 이벤트 처리 함수 만드는 법
      timer1.Start();
    }

    private void Timer1_Tick(object sender, EventArgs e)
    {
      label1.Location = new Point(
        ClientSize.Width / 2 - label1.Width / 2,
        ClientSize.Height / 2 - label1.Height / 2);
      label1.Text = DateTime.Now.ToString();
    }

        private void label1_Click(object sender, EventArgs e)
        {

        }
    }
}

현재시간을 출력하는 프로그램이다.

public Form1()
    {
      InitializeComponent();
      label1.Font = new Font("맑은 고딕", 30, FontStyle.Bold);
      label1.ForeColor = Color.Blue;
    }

폼의 폰트와 포어컬러를 설정해주었다.

private void Form1_Load(object sender, EventArgs e)
    {
      label1.Text = "";
      timer1.Interval = 1000;
      timer1.Tick += Timer1_Tick; // 이벤트 처리 함수 만드는 법
      timer1.Start();
    }

폼이 로드될 때

label1을 빈칸으로 설정해주었다.

interval속성사용하여 간격을 1000으로 설정해주었다.(밀리세컨드 단위로 계산)

timer의 tick 이벤트 핸들러를 사용하여 

Timer_Tick함수를 계속 더해주는 코드를 작성하였다.

timer를 시작한다.

private void Timer1_Tick(object sender, EventArgs e)
    {
      label1.Location = new Point(
        ClientSize.Width / 2 - label1.Width / 2,
        ClientSize.Height / 2 - label1.Height / 2);
      label1.Text = DateTime.Now.ToString();
    }

위에서 선언한 Timer_Tick함수의 구현부이다.

1밀리세컨드마다 label1의 위치를 중앙으로 재설정해준 뒤

텍스트를 datetime구조체의 now 프로퍼티를 사용하여 string의 값으로 반환해준다.

Timer_Tick함수의 위치변경 설정 때문에

반응형어플처럼 창의 크기에따라 위치가 계속 재설정된다.


[3]Datetime Picker

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace _023_dateTimePicker
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
    }

    private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
    {
      DateTime today = DateTime.Today;
      DateTime Sday = dateTimePicker1.Value;

      textBox1.Text 
        = today.Subtract(Sday).TotalDays.ToString("0");  
    }
  }
}

Datetime Picker를 사용하여 값을 받아 선택한 날짜부터 오늘까지 며칠이 지났는지 계산하는 프로그램이다.

private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
    {
      DateTime today = DateTime.Today;
      DateTime Sday = dateTimePicker1.Value;

      textBox1.Text 
        = today.Subtract(Sday).TotalDays.ToString("0");  
    }

datetime 타입 today를 오늘로 설정해주고

sday를 datetime picker에서 받아온 값으로 설정해준다.

textbox1의 텍스트를 today-sday의 totalday프로퍼티를 사용하여 소수점 없이 string타입으로 출력해준다.

7일에 7일을 골랐는데 -1이 출력되는건 이유를 찾아봐야겠다.


[4]동영상 플레이어

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace _024_wmp
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
      OpenFileDialog ofd = new OpenFileDialog();  
      if(ofd.ShowDialog() == DialogResult.OK)
        axWindowsMediaPlayer1.URL = ofd.FileName;
    }
  }
}

파일을 선택하여 동영상을 재생하는 프로그램이다.

private void button1_Click(object sender, EventArgs e)
    {
      OpenFileDialog ofd = new OpenFileDialog();  
      if(ofd.ShowDialog() == DialogResult.OK)
        axWindowsMediaPlayer1.URL = ofd.FileName;
    }

openfiledialog 타입의 ofd를 초기화하여 선언해준다.

if ofd의 showdialog함수를 실행하여 파일탐색기를 열어 dialogresult가 ok되어 true이면

영상플레이어의 url을 선택된 ofd의 이름으로 저장해준다.

이 후엔 영상 플레이어가 url에 해당하는 영상을 재생한다.

ofd.ShowDialog()

영상이 없어서 빈칸으로 대체합니다.

 

'VS-02분반수업' 카테고리의 다른 글

VS02(22-04-15)  (0) 2022.04.20
VS02(22-04-06)  (0) 2022.04.09
VSP02(22-03-30)  (0) 2022.04.06
VSP02(2022-03-23)  (0) 2022.03.31
VSP02(2022-03-16)  (0) 2022.03.23
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2025/04   »
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 29 30
글 보관함