我目前正在使用反向波兰表示法。除指数数学外,我能够执行所有操作。我知道C#sharps使用Math.Pow
执行指数数学运算,但在我的代码中使用它会给我一个错误'System.Collections.Generic.Stack<T>.Push(T)' is a 'method', which is not valid in the given context
。您可以在上一个if else
语句中找到具体问题。知道如何正确地纠正或创建一种执行指数数学的方法吗?
代码
private string inputValue = "";
private void RPNCalc(string rpnValue)
{
Stack<int> stackCreated = new Stack<int>();
stackCreated.Clear();
string[] inputArray = rpnValue.Split();
int end = inputArray.Length - 1;
int numInput;
int i = 0;
do
{
if ("=+-*/%^".IndexOf(inputArray[i]) == -1)
{
try
{
numInput = Convert.ToInt32(inputArray[i]);
stackCreated.Push(numInput);
}
catch
{
MessageBox.Show("Please check the input");
}
}
else if (inputArray[i]== "+")
{
try
{
int store1 = stackCreated.Pop();
int store2 = stackCreated.Pop();
stackCreated.Push(store2 + store1);
}
catch
{
}
}
else if (inputArray[i]== "-")
{
try
{
int store1 = stackCreated.Pop();
int store2 = stackCreated.Pop();
stackCreated.Push(store2 - store1);
}
catch
{
}
}
else if (inputArray[i]== "%")
{
try
{
int store1 = stackCreated.Pop();
int store2 = stackCreated.Pop();
stackCreated.Push(store2 % store1);
}
catch
{
}
}
else if (inputArray[i]== "*")
{
try
{
int store1 = stackCreated.Pop();
int store2 = stackCreated.Pop();
stackCreated.Push(store2 * store1);
}
catch
{
}
}
else if (inputArray[i]== "/")
{
try
{
int store1 = stackCreated.Pop();
int store2 = stackCreated.Pop();
stackCreated.Push(store2 / store1);
}
catch
{
}
}
else if (inputArray[i] == "^")
{
try
{
int store1 = stackCreated.Pop();
int store2 = stackCreated.Pop();
stackCreated.Push.Math.Pow(store1, store2);
}
catch
{
}
}
}
while(i++ < end && inputArray[i]!= "=" && stackCreated.Count != 0);
string result = inputValue + " " + stackCreated.Pop().ToString() + Environment.NewLine;
TxtOutputBox.AppendText(result);
TxtInputBox.Clear();
}
答案 0 :(得分:3)
应该是:
stackCreated.Push((int)Math.Pow(store1, store2));
这将执行电源操作,然后将结果推送到堆栈。
就像在做:
int tmp = (int)Math.Pow(store1, store2);
stackCreated.Push(tmp);
另请注意,Math.Pow
适用于double
。您的整数(store1
和store2
)将自动转换为double
,但您需要告诉编译器将结果强制转换为int
。< / p>