我在c#中很新!任何人都可以帮我如何在WPF中创建的计算器中添加一个sqrt按钮。我在这里粘贴的代码工作正常,但我必须添加另一个应该是平方根的按钮,但我不知道该怎么做。请任何人帮助我,我真的很感激
using System;
using System.Windows;
using System.Windows.Controls;
namespace MyCalculatorv1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
// all button 0 to 9 go here.
private void Button_Click_1(object sender, RoutedEventArgs e)
{
Button b = (Button) sender;
tb.Text += b.Content.ToString();
}
// equal button goes here
private void Result_click(object sender, RoutedEventArgs e)
{
try
{
result();
}
catch (Exception err)
{
tb.Text = "Error!";
}
}
private void result()
{
String op;
int iOp = 0;
if (tb.Text.Contains("+"))
{
iOp = tb.Text.IndexOf("+");
}
else if (tb.Text.Contains("-"))
{
iOp = tb.Text.IndexOf("-");
}
else if (tb.Text.Contains("*"))
{
iOp = tb.Text.IndexOf("*");
}
else if (tb.Text.Contains("/"))
{
iOp = tb.Text.IndexOf("/");
}
else
{
//error
}
op = tb.Text.Substring(iOp, 1);
double op1 = Convert.ToDouble(tb.Text.Substring(0, iOp));
double op2 = Convert.ToDouble(tb.Text.Substring(iOp + 1, tb.Text.Length - iOp - 1));
if (op == "+")
{
tb.Text += "=" + (op1 + op2);
}
else if (op == "-")
{
tb.Text += "=" + (op1 - op2);
}
else if (op == "*")
{
tb.Text += "=" + (op1 * op2);
}
else
{
tb.Text += "=" + (op1 / op2);
}
}
private void Off_Click_1(object sender, RoutedEventArgs e)
{
Application.Current.Shutdown();
}
private void Del_Click(object sender, RoutedEventArgs e)
{
tb.Text = "";
}
private void R_Click(object sender, RoutedEventArgs e)
{
if (tb.Text.Length > 0)
{
tb.Text = tb.Text.Substring(0, tb.Text.Length - 1);
}
}
private void about(object sender, RoutedEventArgs e)
{
MessageBox.Show("simple calculator");
}
}
}
答案 0 :(得分:1)
XAML:
<Grid>
<Button Content="√" HorizontalAlignment="Left" Margin="145,10,0,0" VerticalAlignment="Top" Width="75"
Click="OnSquareRootClick"/>
<TextBox x:Name="txtNumber" HorizontalAlignment="Left" Height="23" Margin="10,10,0,0" Text="" VerticalAlignment="Top" Width="120"/>
<TextBox x:Name="txtResult" HorizontalAlignment="Left" Height="23" Margin="240,10,0,0" Text="" VerticalAlignment="Top" Width="120"/>
</Grid>
代码背后:
private void OnSquareRootClick(object sender, RoutedEventArgs e)
{
double number;
var isDouble = double.TryParse(this.txtNumber.Text, out number);
if (isDouble)
{
this.txtResult.Text =
string.Format(
"{0}{1} = {2}",
"\u221A",
this.txtNumber.Text,
Math.Round(Math.Sqrt(number), 2));
}
}