所以我必须为类制作 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;
最佳答案
要解决非数字输入的崩溃问题,您可以使用 Double.TryParse 而不是 Double.Parse:
if (!Double.TryParse(heightTxt.Text, out height)) {
MessageBox.Show("Not a valid input.");
return;
}
要解决显示到小数点后 2 位的问题,请使用 BMI.ToString("#.##"),正如其他人评论的那样
关于c# - 如何在c#中只显示小数点后2个空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42332527/