2009年12月14日月曜日

身長、体重からBMI値を求め、肥満度を判定するWindows フォームを利用したGUIアプリケーションを作成してみる。
フォーム部分


コードエディタ部分
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;


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


        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                /* 入力された身長をdouble型のParseメソッド
                 を使用してもじれたを数値型に変換して
                 さらに単位をcmからmに変換して取得 */
                var height = double.Parse(textBox1.Text) / 100;


                /* 体重を身長と同様に(こちらは変換しなくてよい)
                  取得 */
                var weight = double.Parse(textBox2.Text);


                // BMI値の計算
                double bmi = weight / (height * height);


                string s;


                // BMI値から肥満度を判定
                if (bmi < 18.5)
                {
                    s = "低体重";
                }
                else if (bmi < 25)
                {
                    s = "標準体重";
                }
                else if (bmi < 30)
                {
                    s = "標準以上";
                }
                else
                {
                    s = "肥満";
                }


                // TextBox3にメッセージを設定
                textBox3.Text = String.Format
                    ("{0}¥r¥nBMI:{1:#.#}", s, bmi);
            }
            /* 例外が発生した場合textBox3
             * 例外の原因の詳細情報を表示 */
            catch (Exception error)
            {
                textBox3.Text = error.Message;
            }
        }
    }
}

0 コメント:

コメントを投稿