【发布时间】:2017-02-19 20:30:05
【问题描述】:
所以我必须为课堂制作一个 BMI 计算器,但我只需要一些帮助。
当我运行我的程序时,输入 2 个值然后计算,它会显示正确的答案,但小数点后有 8 位数字。
如果我输入除数字以外的任何输入,它会使我的程序崩溃,我该如何解决这个问题?
这是我的代码:
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 WindowsFormsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void weightTxt_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
double BMI = 0;
double weight = 0;
double height = 0;
height = Double.Parse(heightTxt.Text);
weight = Double.Parse(weightTxt.Text);
// declaring and assigning
if (weight > 300 || weight < 10)
{
MessageBox.Show("Not a valid input.");
}
if (height > 2.2 || height < 0.2)
{
MessageBox.Show("Not a valid input.");
}
// checking that values meet parameters
BMI = weight / (height * height);
string result = Convert.ToString(BMI);
resultLbl.Text = "Your BMI is : " + result;
【问题讨论】:
-
string result = BMI.ToString("#.##");