2011-11-24 37 views
-2
using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 

namespace WindowsFormsApplication1 
{ 
    public partial class Form1 : Form 
    { 
     double x, y; 

     public Form1() 
     { 
      InitializeComponent(); 

      // Initialize input points to zero 
      textBox1.Text = "0"; 
      textBox2.Text = "0"; 
      x = Double.Parse(textBox1.Text); 
      y = Double.Parse(textBox2.Text); 
     } 

     private void radioButton1_CheckedChanged(object sender, EventArgs e) 
     {   
      x = Double.Parse(textBox1.Text); 
      y = Double.Parse(textBox2.Text); 

      if (radioButton1.Checked) 
      { 
       x = x/(System.Math.Pow(x, 2) + System.Math.Pow(y, 2)); 
       y = -y/(System.Math.Pow(x, 2) + System.Math.Pow(y, 2)); 
       textBox1.Text = x.ToString(); 
       textBox2.Text = y.ToString(); 
      } 
     } 

     private void radioButton2_CheckedChanged(object sender, EventArgs e) 
     { 
      x = Double.Parse(textBox1.Text); 
      y = Double.Parse(textBox2.Text); 

      if (radioButton2.Checked) 
      { 
       x = x/(System.Math.Pow(x, 2) + System.Math.Pow(y, 2)); 
       y = -y/(System.Math.Pow(x, 2) + System.Math.Pow(y, 2)); 
       textBox1.Text = x.ToString(); 
       textBox2.Text = y.ToString(); 
      } 
     } 
    } 
} 

我试图“重新模拟”我的问题,这里是代码。尝试在每个文本框中输入1的值,然后单击未选中的单选按钮。 textbox1的预期输出应该是0.5,textbox2应该给-0.5,但是我在textbox2中得到-0.8。C#错误的数学结果

+0

无法重现。完整的代码示例或它没有发生。 – sepp2k

+0

适用于我 - .NET 4 - 结果**是** -0.5 .... –

+0

这里没有错误([在线演示](http://ideone.com/cPSHv),使用乔恩的代码) – Nasreddine

回答

4

看到新代码后

好了,这里是你修改的代码很短,但完整版本:

using System; 

class Test 
{ 
    static void Main() 
    { 
     double x = 1; 
     double y = 1; 
     x = x/(x * x + y * y); 
     y = -y/(y * y + x * x); 


     Console.WriteLine(x); 
     Console.WriteLine(y); 
    } 
} 

现在,我得到0.5,-0.8 - 其原因是相当清楚的。在计算中,x和y的第一行的起始都是1,所以表达式为:

x = 1.0/(1.0 * 1.0 + 1.0 * 1.0); 

所以x为0.5。现在,影响线计算的,其变为:

y = -1.0/(1.0 * 1.0 + 0.5 * 0.5) 

换句话说,Y = -1.0/1.25 ...其等于-0.8。

我怀疑你不想,直到你做了计算,例如赋值给xy

x2 = x/(x * x + y * y); 
y2 = -y/(y * y + x * x); 

x = x2; 
y = y2; 

我相信会解决您的问题。值得尝试学习如何编写一个简短但完整的程序来帮助诊断这类事情。


原来的答复

无法重现:

using System; 

public class Program 
{ 
    static void Main(string[] args) 
    { 
     double x = 1; 
     double y = 1; 

     x = -x/((x*x) + (y*y)); 
     Console.WriteLine(x); 
    }   
} 

结果:-0.5

请自己尝试这个节目,如果它打印-0.5你(作为我完全期待它),看看你是否可以想出一个类似的简短但完整的程序演示了这个问题。我怀疑,在尝试将当前代码转换为简短但完整的程序的过程中,您会发现该错误。

+1

这应该是答案还是评论? – Gabe

+1

其他人评论“无法复制”;这是相同的想法,但在注释中包含格式正确的代码示例是不可能的,所以...... :) –

+1

如果答案是用户错了,并且没有问题,那么是的,它应该是一个答案。 – Brandon