Tuesday, July 14, 2009

How do you calculate the sum of two numbers in C#?

I'm going through a C# tutorial and am trying to create a VERY simple calculator (a Windows Application).





It should work like this:





You type one floating point number into a textbox (Number1).


You type one floating point number into a textbox (Number2).


You click the CALCULATE button.


The sum of Number1 and Number2 displays in a textbox called Sum.





All I need is the one line of code to apply to the CALCLATE button to get that sum to display in the Sum box.

How do you calculate the sum of two numbers in C#?
It's two lines of code within the event handler function:





double result = Double.Parse(Number1.Text) + Double.Parse(Number2.Text);


Sum.Text = result.ToString();
Reply:The main trick is that you need to convert the strings from the text boxes into floating point values. Try:





Sum.Text = Convert.ToDouble( Number1.Text ) +


Convert.ToDouble( Number2.Text )





You can get fancy and use an IFormatProvider too so it'll work in Europe as well as the US. This would be proper for a commercial application, but overkill for homework unless you want brownie points.
Reply:Sum.text = Sum(Number1.Text, Number2.Text);





Try that.
Reply:About the first error you mentioned. This error occurs when you typed the name of a field, method,... incrorrectly. Note that if you type the name without pay attention to it's character case, You will recieve that error. For example this line is correct:





Sum.Text="";





But this one cause the error:





Sum.text="";





Because in first sample you typed the name of the property exactly as defined but in seceond case you only type a name like that, not itself.





And an other thing. When you acquire the value of two Text Boxes, you should convert them into a type which you could done the action by that. In your case you should convert the value of Number1 and Number2 into double. You can use this sample:





double dSum;


dSum = Convert.ToDouble(Number1.Text);


dSum += Convert.ToDouble(Number2.Text);





Sum.Text=dSum.ToString();





You can also use this line as the last line of code above:


Sum.Text=Convert.ToString(dSum);





And these are same each other.





Be Succeed.

local florist

No comments:

Post a Comment