[英]Button doesn't make value appear in textBox
我想2個文本框后我按下一個按鈕顯示的數字,但是當我按下一個按鈕,了一個TextBox顯示其數量和第二個沒有。
private void Calculating(object sender, EventArgs e)
{
if (textBox6.Text != "")
{
rutr = Double.Parse(textBox6.Text);
rutd = rutr * 2;
textBox7.Text = (rutd).ToString();
textBox8.Text = (3 / 4 * pi * rutr * rutr * rutr).ToString();
}
}
textBox8
沒有顯示正確的數字。
行為不當的根本原因是整數除法 : 3 / 4 == 0
應該是
// The formula seems to be a volume of a sphere: 3/4 * Pi * r**3
// It's a physical world, that's why 3.0 - double, not 3M - decimal
textBox8.Text = (3.0 / 4.0 * pi * rutr * rutr * rutr).ToString();
請注意浮點數 3.0
而不是整數 3
。 另一個建議是使用double.TryParse
:如果我們可以解析用戶輸入( textBox6.Text
),然后進行計算
private void Calculating(object sender, EventArgs e) {
double rutr = 0.0;
// If we can parse textBox6.Text into double rutr
if (double.TryParse(textBox6.Text, out rutr)) {
rutd = rutr * 2;
textBox7.Text = (rutd).ToString();
textBox8.Text = (3.0 / 4.0 * pi * rutr * rutr * rutr).ToString();
}
}
編輯 :從技術上講,有可能在textBox8
產生空白 ( ""
),請參閱下面的評論(這本身就是一個有趣的問題)。 這是代碼
using System.Globalization;
...
CultureInfo ci = (CultureInfo.CurrentCulture.Clone() as CultureInfo);
// The idea: double.NaN will be displayed as blank
ci.NumberFormat.NaNSymbol = "";
CultureInfo.CurrentCulture = ci;
double pi = Math.Sqrt(-1); // pi is double.NaN - imaginary unit
...
// 0 * NaN * rutr * rutr * rutr == NaN which is printed as empty string
textBox8.Text = (3 / 4 * pi * rutr * rutr * rutr).ToString();
在這里,我們利用以下事實: 0 * double.NaN == double.NaN
。 但是,我不相信這種錯誤
您應該使用后綴來告訴編譯器數字文字不被視為int。
textBox8.Text = (3M / 4M * pi * rutr * rutr * rutr).ToString();
https://docs.microsoft.com/en-US/dotnet/csharp/language-reference/keywords/decimal
以下是可能的后綴列表:
F:浮點數D:雙精度U:uint L:長UL:ulong M:十進制
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.