Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Learning C#, Math equation not resulting as expected

Tags:

c#

math

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

like image 527
Nathan Gardner Avatar asked Feb 27 '26 20:02

Nathan Gardner


2 Answers

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;
like image 163
Sergey Kalinichenko Avatar answered Mar 01 '26 10:03

Sergey Kalinichenko


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.

like image 30
Mike Christensen Avatar answered Mar 01 '26 09:03

Mike Christensen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!