Nathan Gardner
Nathan Gardner

Reputation: 21

Learning C#, Math equation not resulting as expected

Learning C#, Math equation not resulting as expected. This is apart of my homework. I do not understand why the result are not coming out as them should..

First equation

m=2
n=1

int sideA = (m^2) - (n^2);

result -3

Second equation

x1=2
x2=7

float Xmid = (x1 + x2)/2;

result 4

Upvotes: 2

Views: 160

Answers (2)

Mike Christensen
Mike Christensen

Reputation: 91590

Your first line of code:

int sideA = (m^2) - (n^2);

Is basically m XOR 2 minus n XOR 2. XOR is a bitwise operator that results in the bits where one is true but not both. For more information on the exclusive OR operator, consult Wikipedia. If you're trying to raise m to the power of 2, try something like:

int sideA = Math.Pow(m, 2) - Math.Pow(n, 2);

Your second line of code:

float Xmid = (x1 + x2)/2;

Is (2 + 7) which is 9, divided by the integer 2 which is 4.5, however because dividing an integer by another integer will always result in an integer, only the integer portion of the result will be kept. The fact that you're assigning this expression to a float is irrelevant.

You might want to try:

float Xmid = (x1 + x2)/2.0;

or:

float Xmid = (x1 + x2)/2f;

or declare x1 and x2 as floats, both which will yield 4.5.

Upvotes: 4

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

This is because in C# ^ means XOR, not "raised to the power of". To square a number, use

Math.Pow(x, 2)

or simply

x * x

Also dividing integers truncates the fractional part. Use decimal, double, or float to get 3.5 as the midpoint of 3 and 4:

float x1=2
float x2=7

float Xmid = (x1 + x2)/2;

Upvotes: 11

Related Questions