Math In C#
Intro:
When working with multiplying, dividing, subtracting, numbers from textBox's, you must always parse it. If you do not know how to do this, please see my parsing tutorial.
When working with decimals in C# "45.5235" you must use a floating point or a double. The difference between the two is this:
Float is a floating point on the end, it can hold up to 7 digits. (32 bit)
Double can have up to 16 digits. (64 bit)
Getting Started:
Create two textbox's, and a button.
Inside of the button, insert the following:
Code
double num1 = double.Parse(textBox1.Text);
double num2 = double.Parse(textBox2.Text);
double answer = num1 + num2;
MessageBox.Show(answer.ToString());The first line creates a new double variable, and parses the value from the first textbox.
The second line creates a new double variable, and parses the value from the second textbox.
The third line sets up another double variable, that adds the first two number.
Finally, the last line displays the answer.
If you want to do something other than add you need to use one of the other mathematical operators:
Code
+ Adds
- Subtracts
/ Divides
* MultipliesSpoiler (Click to View)
Conclusion:
Calculating in C# can be used for so many different things. Whether its balancing your check book, finding out how much money you will make in a year, or calculating packets!
Code:
[IMG]http://i54.[censored].com/6yz9zp.jpg[/IMG]
Code
private void button4_Click(object sender, EventArgs e)
{
double num1 = double.Parse(textBox1.Text);
double num2 = double.Parse(textBox2.Text);
double answer = num1 + num2;
MessageBox.Show(answer.ToString());
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
double num1 = double.Parse(textBox1.Text);
double num2 = double.Parse(textBox2.Text);
double answer = num1 / num2;
MessageBox.Show(answer.ToString());
}
private void button2_Click(object sender, EventArgs e)
{
double num1 = double.Parse(textBox1.Text);
double num2 = double.Parse(textBox2.Text);
double answer = num1 * num2;
MessageBox.Show(answer.ToString());
}
private void button3_Click(object sender, EventArgs e)
{
double num1 = double.Parse(textBox1.Text);
double num2 = double.Parse(textBox2.Text);
double answer = num1 - num2;
MessageBox.Show(answer.ToString());
}Also, I do not recommend reusing variable names, I just did it to be lazy!
http://www.pulsecodes.info
Computer and Information Science major.
Information Technology Apprentice.
Freelance Programmer.
Computer and Information Science major.
Information Technology Apprentice.
Freelance Programmer.

