I want 2 textBoxes to show numbers after I press a button, but when I press a button, one textBox shows number in it and the second doesn't.
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();
}
}
The textBox8
doesn't show correct number.
The very cause of the misbehavior is integer division : 3 / 4 == 0
should be
// 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();
please, notice floating point 3.0
value instead of integer 3
. Another suggestion is to use double.TryParse
: if we can parse user input ( textBox6.Text
) then do it and compute
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();
}
}
Edit : Technically, it's possible to produce blank ( ""
) in the textBox8
, see comments below (it's an interesting problem itself). Here's the code
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();
Here we exploit the fact that, 0 * double.NaN == double.NaN
. However, I don't believe in this kind of error
You should use a suffix to tell the compiler that the numeric literals are not treated as int.
textBox8.Text = (3M / 4M * pi * rutr * rutr * rutr).ToString();
https://docs.microsoft.com/en-US/dotnet/csharp/language-reference/keywords/decimal
Here is a list of possible suffixes:
F: float D: double U: uint L: long UL: ulong M: decimal
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.