简体   繁体   English

数学表达式的问题

[英]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#中使用指数运算符时,编译器报告“ 运算符^不能应用于int和double类型的操作数。 ”虽然在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 为了避免C#错误,我更新了代码以使用Math.Pow(),它输出错误

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. 在Excel中执行相同的公式时,按预期给出108.0660172。 =1 * (1 +1) + 75 * 1 * (1 + 1) ^ 0.5 = 1 *(1 + 1)+ 75 * 1 *(1 + 1)^ 0.5

Please help me resolve this. 请帮我解决这个问题。

In C# ^ is not a power operator. 在C#中,^不是幂运算符。 It's a Xor operator. 它是一个Xor运算符。 Here is the documentation about it: ^ Operator (C# Reference) 这是关于它的文档: ^运算符(C#参考)

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. 至于评估为12.32的原因是1 *(1 + 1)+ 75 * 1 *(1 + 1)等于152而sqrt(152)约为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. 另一方面,在VB和Excel中,它被评估为1 *(1 + 1)+ 75 * 1 * sqrt(2),即108.06。 In c# you can express it as double i = 1 * (1 + 1) + 75 * 1 * Math.Pow((1 + 1),0.5); 在c#中你可以表示为double i = 1 * (1 + 1) + 75 * 1 * Math.Pow((1 + 1),0.5);

Power of 0.5 equals square root. 0.5的幂等于平方根。

Square root of your i (2 + 150 = 152) in fact is ~12,33. 你的i的平方根(2 + 150 = 152)实际上是~12,33。

Pow() returns the correct answer, be sure to use brackets over what you want to power. Pow()返回正确的答案,请务必使用括号超过您想要的功率。

Your VB calculation will be procede as follows: 您的VB计算将按如下方式进行:

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

To get the same result in C# you have to write it as: 要在C#中获得相同的结果,您必须将其写为:

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

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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM