这段代码是一个计算器程序的一部分,用于处理输入的字符串中的数学函数。如果输入的字符是 's'、'c'、't'、'l' 中的任意一个,就会将其后面的数字解析出来,并根据函数类型计算出结果,然后将结果压入栈中。函数类型包括 sin、cos、tan、sqrt 和 log,分别代表正弦函数、余弦函数、正切函数、平方根和自然对数。如果输入的字符不是这些函数类型,则会提示错误。

代码片段如下:

else if (c == 's' || c == 'c' || c == 't' || c == 'l') { bool hasDot = false; bool start = false; string funName = ""; int decimalPartIndex = 0;

string intPart = "";
string decimalPart = "";

double num = 0;

//检索数字
for (; j < str.Length; j++)
{
    if ((str[j] >= '0' && str[j] <= '9') || str[j] == '.')
    {
        if (start == false)
            start = true;

        if (str[j] == '.')
        {
            if (!hasDot)
            {
                hasDot = true;
                decimalPartIndex = j;
                continue;
            }
            else
            {
                MessageBox.Show("数据存在错误");
                return -1;
            }
        }
        else
        {
            if (hasDot)
                decimalPart += str[j];
            else
                intPart += str[j];
        }
    }
    else
    {
        if (start)
        {
            i = j - 1;
            break;
            //end
        }
        else
        {
            funName += str[j];
            continue;
        }
    }
}

if (intPart.Length > 0)
{
    num = double.Parse(intPart);
}
else
{
    num = 0;
}

if (hasDot)
{
    if (decimalPart.Length > 0)
        num += 0.1 * double.Parse(decimalPart);
    else
        num += 0.0;
}

if (funName.Contains("sin"))
    num = Math.Sin(num);
else if (funName.Contains("cos"))
    num = Math.Cos(num);
else if (funName.Contains("tan"))
    num = Math.Tan(num);
else if (funName.Contains("sqrt"))
    num = Math.Sqrt(num);
else if (funName.Contains("log"))
    num = Math.Log(num);
else
    MessageBox.Show("运算还有错误");

nums.Push(num);

}

C# 代码解析:如何使用 C# 编写数学函数计算器

原文地址: https://www.cveoy.top/t/topic/ot0D 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录