2017-02-19 21 views
2

Так что я должен сделать калькулятор BMI для класса, но мне просто нужна помощь с несколькими вещами.как показывать только 2 пробела после десятичного числа в C#

  1. Когда я запускаю свою программу, положить в 2-х значениях, то вычислить, он отображает правильный ответ, но есть как 8 цифр после запятой.

  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 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; 
+1

'строка результат = BMI.ToString ("# ##.");' – shash678

ответ

1

Чтобы решить проблему сбоев на нечисловом вход, вы можете использовать Double.TryParse вместо Double.Parse:

if (!Double.TryParse(heightTxt.Text, out height)) { 
    MessageBox.Show("Not a valid input."); 
    return; 
} 

Чтобы устранить проблему с отображением до двух знаков после запятой, используйте BMI.ToString ("#. ##"), как другие комментировали

+0

Это работает, но я не знаю, почему LOL Спасибо, плохо выглядеть в документации – Sal

0
 double weight = 0; 
     double height = 0; 

     if (Double.TryParse(weightTxt.Text, out weight) && Double.TryParse(heightTxt.Text, out height)) { 
      if (weight > 300 || weight < 10 || height > 2.2 || height < 0.2) 
      { 
       MessageBox.Show("Not a valid input."); 
      } 

      double BMI = weight/(height * height); 

      /*Two ways for converting to two didges:*/ 

      // 1. 

      // Round to two didgets 
      double result = Math.Round(BMI, 2); 
      // convert result to string 
      string resultString = Convert.ToString(result); 

      // 2. 
      string resultString = BMI.ToString("#.##")    
     }  
0

Мальчик, если был никель для каждой домашней работы в stackoverflow.

  double BMI = 0; 
      double weight = 0; 
      double height = 0; 

      //use try parse to test if the value is convertable 
      if (!Decimal.TryParse(heightTxt.Text,out height)) 
      { 
       MessageBox.Show("Not a valid input."); 
       return; 
      } 

      if (!Decimal.TryParse(weightTxt.Text, out weight)) 
      { 
       MessageBox.Show("Not a valid input."); 
       return; 
      } 

      // declaring and assigning 
      if (weight > 300 || weight < 10) 
      { 
       MessageBox.Show("Not a valid input."); 
       //return so the method dosnt try to do the rest of the code 
       return; 

      } 
      if (height > 2.2 || height < 0.2) 
      { 
       MessageBox.Show("Not a valid input."); 
       return; 
      } 

      BMI = weight/(height * height); 
      //this is how you format the nuumber to two decimal places 
      string result = BMI.ToString("#.##"); 
      resultLbl.Text = "Your BMI is : " + result; 
Смежные вопросы