英文:
How to I do a square root without using math.sqrt() in c#?
问题
When I run my program and put 0.00000001 to root nothing happens but when I put the whole number it runs fine. I'm expecting the method to work for decimals too. I also need a Message box with the message "Please enter a positive number when a negative answer is put in.
{
int number = Convert.ToInt32(txtNumber.Text);
double root = 1;
int i = 0;
//用于计算平方根的巴比伦方法
while(true)
{
i = i + 1;
root =(number / root + root)/ 2;
if(i == number + 1){break; }
}
lbResult.Text = root.ToString();
}```
<details>
<summary>英文:</summary>
When I run my program and put 0.00000001 to root nothing happens but when I put the whole number it runs fine. I'm expecting the method to work for decimals too. I also need a Message box with the message "Please enter a positive number when a negative answer is put in.
private void btnCalc_Click(object sender, EventArgs e)
{
int number = Convert.ToInt32(txtNumber.Text);
double root = 1;
int i = 0;
//The Babylonian Method for Computing Square Roots
while (true)
{
i = i + 1;
root = (number / root + root) / 2;
if (i == number + 1) { break; }
}
lbResult.Text = root.ToString();
}
</details>
# 答案1
**得分**: 2
我建议使用巴比伦算法:
```csharp
private void btnCalc_Click(object sender, EventArgs e)
{
double number = Convert.ToDouble(txtNumber.Text);
if (number <= 0)
{
MessageBox.Show("请输入一个正数");
return;
}
double x = number;
double y = 1;
double tol = 0.000001;
while (x - y > tol)
{
x = (x + y) / 2;
y = number / x;
}
lbResult.Text = x.ToString();
}
英文:
I suggest a Babylonian algorithm:
private void btnCalc_Click(object sender, EventArgs e)
{
double number = Convert.ToDouble(txtNumber.Text);
if(number <= 0)
{
MessageBox.Show("Please enter a positive number");
return;
}
double x = number;
double y = 1;
double tol = 0.000001;
while (x - y > tol)
{
x = (x + y) / 2;
y = number / x;
}
lbResult.Text = x.ToString();
}
答案2
得分: 1
"I'm expecting the method to work for decimals too."
然后也许不要使用输入来做这个,而是解析为除了 int
之外的其他类型:
decimal number = Convert.ToDecimal(txtNumber.Text);
你需要一个 decimal
:
英文:
> I'm expecting the method to work for decimals too.
Then maybe don't do this with the input, and parse to something other than int
:
int number = Convert.ToInt32(txtNumber.Text);
You want a decimal
:
var number = Convert.ToDecimal(txtNumber.Text);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论