AbrahamJP
AbrahamJP

Reputation: 3430

Problem with mathematical expression

While using exponential operator in C#, the compiler was reporting "Operator ^ cannot be applied to operands of type int and double." While the same was compiling without any errors in VB.NET.

//C# Code, error while compiling
decimal i = 1 * (1 + 1) + 75 * 1 * (1 + 1) ^ 0.5;

'VB.NET Code. Compiled without errors 
Dim i as decimal = 1 * (1 + 1) + 75 * 1 * (1 + 1) ^ 0.5 'outputs 108.066017177982 as expected

To circumvent the C# error, I updated the code to use Math.Pow() which was giving wrong output

decimal i = 1 * (1 + 1) + 75 * 1 * (1 + 1);
i = (decimal)Math.Pow((double)i, 0.5);
Console.WriteLine(i); //Outputs 12.328828005938 instead of 108.0660172

//Next i changed the datatype to double, still same results
double i = 1 * (1 + 1) + 75 * 1 * (1 + 1);
i = Math.Pow(i, 0.5);
Console.WriteLine(i); //Outputs 12.328828005938 instead of 108.0660172

While executing the same formula in Excel, gives 108.0660172 as expected. =1 * (1 +1) + 75 * 1 * (1 + 1) ^ 0.5

Please help me resolve this.

Upvotes: 2

Views: 609

Answers (4)

Giorgi
Giorgi

Reputation: 30873

In C# ^ is not a power operator. It's a Xor operator. Here is the documentation about it: ^ Operator (C# Reference)

As for the reason why it evaluates to 12.32 is that 1 * (1 + 1) + 75 * 1 * (1 + 1) equals to 152 and sqrt(152) is about 12.32.

On the other hand in VB and Excel it is evaluated as 1 * (1 + 1) + 75 * 1 * sqrt(2) which is 108.06. In c# you can express it as double i = 1 * (1 + 1) + 75 * 1 * Math.Pow((1 + 1),0.5);

Upvotes: 8

vgru
vgru

Reputation: 51214

You applied square root to the entire expression.

Try this instead:

double lastPart = (1 + 1);
double sqrt = Math.Pow(lastPart, 0.5);
double i = 1 * (1 + 1) + 75 * 1 * sqrt;
Console.WriteLine(i); 

Upvotes: 1

Oliver
Oliver

Reputation: 45091

Your VB calculation will be procede as follows:

(1 * (1 + 1)) + (75 * 1 * ((1 + 1) ^ 0.5));

To get the same result in C# you have to write it as:

1 * (1 + 1) + 75 * 1 * Math.Pow((1 + 1),0.5);

Upvotes: 4

supertopi
supertopi

Reputation: 3488

Power of 0.5 equals square root.

Square root of your i (2 + 150 = 152) in fact is ~12,33.

Pow() returns the correct answer, be sure to use brackets over what you want to power.

Upvotes: 5

Related Questions