(算术表达式求值) 输入一个由数字、+,-,*,/ 及括号组成的算术表达式, 求其值。
[C#]
using System.Xml;
using System.Xml.XPath;
/*以下为在一个文本框内输入包括文字、数字、计算符号等内容的字符串,然后抛去文字只对数字按输入的操作符进行计算的方法*/
private void textBox1_TextChanged(object sender, EventArgs e)
{
dhx2 = text1.Lines.Length;
//以下声明一个变量为text1中的行位
int hw = 0;
//行位是总行数减一
hw = dhx2 - 1;
//以下声明一个字符串数组记录每一行原始的字符串
string[] mhsj;
mhsj = new string[dhx2];
//以下声明两个字符串数组分别记录每行去掉字符只有数字和计算符号的字符串及将"/"换成"div"可做除法的结果
string[] mhszfhzf = new string[dhx2];
//第一步先将文本框中每行文本中的数字和符号取出,赋给一个新的字符串数组mhszfhzf,这样mhszfhzf每个元素即代表文本框中每行文本中的数字和符号;
try
{
for (int i = 0; i < dhx2; i++)
{
mhsj[i] = text1.Lines[i];
//取出每行字符串中的所有的数字和符号并赋给新的字符串//
string[] dgzf;
dgzf = new string[mhsj[i].Length];
int j, h;
for (j = 0; j < mhsj[i].Length; j++)
{
dgzf[j] = mhsj[i].Substring(j, 1);
//转换%号为乘0.01的数
if (dgzf[j].Equals("%") == true)
{
dgzf[j] = "*0.01";
}
}
//判断/符号是单位符号还是除法符号
for (int k = 0; k < mhsj[i].Length; k++)
{
if (dgzf[k].Equals("/") == true)
{
if (char.IsNumber(dgzf[k + 1], 0) == true)
{
dgzf[k] = dgzf[k];
}
else
{
dgzf[k] = "每";
}
}
}
for (h = 0; h < j; h++)
{
if (char.IsNumber(dgzf[h], 0) == true || char.IsPunctuation(dgzf[h], 0) == true || char.IsSymbol(dgzf[h], 0) == true)
{
mhszfhzf[i] = mhszfhzf[i] + dgzf[h];
}
}
}
}
catch (Exception)
{
}
//第二步再对mhszfhzf中每个字符串元素按数学公式进行计算;
try
{
//将"/"号换成" div "这样就可以做除法;
mhszfhzf1[hw] = mhszfhzf[hw].Replace("/", " div ");
//调用按公式计算的函数Evaluate按输入的公式逐行进行计算,将结果值赋给一个表示每行结果的变量
XmlDocument xd = new XmlDocument();
XPathNavigator jszhs = xd.CreateNavigator();
myhjg = (double)jszhs.Evaluate(mhszfhzf1[hw]);
}
catch (Exception)
{
}
}
private void text1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 13)
{
//按下回车键后将单位数量单价中的结果进行累加
zzjg += myhjg;
jg = zzjg.ToString();
textBox2.Text = jg;
}
}
[C++]
#include "stdafx.h"
#include <cstdlib> // For exit()
using namespace System;
String^ eatspaces(String^ str); // Function to eliminate blanks
double expr(String^ str); // Function evaluating an expression
double term(String^ str, int^ index); // Function analyzing a term
double number(String^ str, int^ index); // Function to recognize a number
String^ extract(String^ str, int^ index); // Function to extract a substring
int main(array<System::String ^> ^args)
{
String^ buffer; // Input area for expression to be evaluated
Console::WriteLine(L"Welcome to your friendly calculator.");
Console::WriteLine(L"Enter an expression, or an empty line to quit.");
for(;;)
{
buffer = eatspaces(Console::ReadLine()); // Read an input line
if(String::IsNullOrEmpty(buffer)) // Empty line ends calculator
return 0;
Console::WriteLine(L" = {0}/n/n",expr(buffer)); // Output value of expression
}
return 0;
}
// Function to eliminate spaces from a string
String^ eatspaces(String^ str)
{
// Array to hold string without spaces
array<wchar_t>^ chars = gcnew array<wchar_t>(str->Length);
int length = 0; // Number of chars in array
// Copy non-space characters to chars array
for each(wchar_t ch in str)
if(ch != ' ')
chars[length++] = ch;
// Return chars array as string
return gcnew String(chars, 0, length);
}
// Function to evaluate an arithmetic expression
double expr(String^ str)
{
int^ index = 0; // Keeps track of current character position
double value = term(str, index); // Get first term
while(*index < str->Length)
{
switch(str[*index]) // Choose action based on current character
{
case '+': // + found so
++(*index); // increment index and add
value += term(str, index); // the next term
break;
case '-': // - found so
++(*index); // decrement index and add
value -= term(str, index); // the next term
break;
default: // If we reach here the string is junk
Console::WriteLine(L"Arrrgh!*#!! There's an error./n");
exit(1);
}
}
return value;
}
// Function to get the value of a term
double term(String^ str, int^ index)
{
double value = number(str, index); // Get the first number in the term
// Loop as long as we have characters and a good operator
while(*index < str->Length)
{
if(str[*index] == L'*') // If it's multiply,
{
++(*index); // increment index and
value *= number(str, index); // multiply by next number
}
else if( str[*index] == L'/') // If it's divide
{
++(*index); // increment index and
value /= number(str, index); // divide by next number
}
else
break; // Exit the loop
}
// We've finished, so return what we've got
return value;
}
// Function to recognize a number
double number(String^ str, int^ index)
{
double value = 0.0; // Store for the resulting value
// Check for expression between parentheses
if(str[*index] == L'(' ) // Start of parentheses
{
++(*index);
String^ substr = extract(str, index); // Extract substring in brackets
return expr(substr); // Return substring value
}
// Loop accumulating leading digits
while((*index < str->Length) && Char::IsDigit(str, *index))
{
value = 10.0*value + Char::GetNumericValue(str[(*index)]);
++(*index);
}
// Not a digit when we get to here
if((*index == str->Length) || str[*index] != '.') // so check for decimal point
return value; // and if not, return value
double factor = 1.0; // Factor for decimal places
++(*index); // Move to digit
// Loop as long as we have digits
while((*index < str->Length) && Char::IsDigit(str, *index))
{
factor *= 0.1; // Decrease factor by factor of 10
value = value + Char::GetNumericValue(str[*index])*factor; // Add decimal place
++(*index);
}
return value; // On loop exit we are done
}
// Function to extract a substring between parentheses
String^ extract(String^ str, int^ index)
{
// Temporary space for substring
array<wchar_t>^ buffer = gcnew array<wchar_t>(str->Length);
String^ substr; // Substring to return
int numL = 0; // Count of left parentheses found
int bufindex = *index; // Save starting value for index
while(*index < str->Length)
{
buffer[*index - bufindex] = str[*index];
switch(str[*index])
{
case ')':
if(numL == 0)
{
array<wchar_t>^ substrChars = gcnew array<wchar_t>(*index - bufindex);
str->CopyTo(bufindex, substrChars, 0, substrChars->Length);
substr = gcnew String(substrChars);
++(*index);
return substr; // Return substring in new memory
}
else
numL--; // Reduce count of '(' to be matched
break;
case '(':
numL++; // Increase count of '(' to be matched
break;
}
++(*index);
}
Console::WriteLine(L"Ran off the end of the expression, must be bad input.");
exit(1);
return substr;
}