CコードでBMIを計算する方法
健康管理とプログラミングを組み合わせて、C(正確にはC++/C#)で自分の体格指数(BMI)を計算する方法をご紹介します。BMIは体重(kg)と身長(m)の比率で求められ、18.5〜24.9 が最も健康的とされています。過度の肥満はがんや心臓病などのリスクを高めます。
必要なもの
- 体重計(ポンド単位)
- メジャー(身長測定用)
手順
- Windows または Linux/Unix に C++(実際は C#)の開発環境を用意し、以下のコードをプロジェクトに貼り付けます。
- コード内の名前空間やクラスはそのまま使用できます。必要に応じて
using文を追加してください。 - 実行後、ウィンドウが表示されるので、体重(ポンド)と身長(インチ)を入力し「Calculate」ボタンを押します。
- 結果欄に「BMI は xx.x で、○○に該当します」と表示されます。
サンプルコード
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 BMIApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnCalculate_Click(object sender, EventArgs e)
{
double weight = string.IsNullOrEmpty(txtWeight.Text) ? 1 : double.Parse(txtWeight.Text);
double height = string.IsNullOrEmpty(txtHeight.Text) ? 1 : double.Parse(txtHeight.Text);
if (weight == 0)
MessageBox.Show("Results will be inaccurate. Weight is not a valid number.");
if (height == 0)
MessageBox.Show("Results will be inaccurate. Height is not a valid number.");
double vmult = cboWeightUnits.SelectedItem.ToString() == "pounds" ? 2.204 : 1;
double hmult = cboHeightUnits.SelectedItem.ToString() == "inches" ? 0.0254 : 1;
double BMI = Math.Round(((weight / vmult) / ((height * hmult) * (height * hmult))) * 10) / 10;
string BMI_description = "";
if (BMI < 16.5) BMI_description = "severely underweight";
else if (BMI >= 16.5 && BMI < 18.5) BMI_description = "underweight";
else if (BMI >= 18.5 && BMI < 25) BMI_description = "normal";
else if (BMI >= 25 && BMI <= 30) BMI_description = "overweight";
else if (BMI > 30 && BMI <= 35) BMI_description = "obese";
else if (BMI > 35 && BMI <= 40) BMI_description = "clinically obese";
else BMI_description = "morbidly obese";
txtResult.Text = string.Format("Your Body Mass Index (BMI) is: {0}. This would be considered {1}.", BMI, BMI_description);
}
}
}
以上の手順で、簡単に自分のBMIを計算し、健康状態を把握できます。
