我需要一些帮助来创建一个函数来显示我的输出并更改我的输出更改时显示的内容

时间:2019-05-30 20:23:53

标签: c++

我正在尝试使函数随输出变化而变化,我认为通过查看代码,您会明白我的意思 但这是一个例子

  
    

回答0

         

表情:4 + 6 +(6 * 4)

         

答案34

         

在我按Enter键之后,它将重置并要求新的          表达式,但显示上一个答案

         

答案34

         

表情:4 + 5

         

答案9

         

点击Enter后再次重置

         

答案9

         

表情:6 + 10

         

答案16

         

点击Enter后再次重置

         

答案16

         

表情:5 * 2

         

答案10

  
// function.h

    void calculateCalc(string & EquationText)
    {
        cout << "Answer " << CalculateExpression(EquationText) << endl;
    }

    void update(string& EquationText)
    {
        string newequation = "";
         newequation = CalculateExpression(EquationText);
         cout << newequation;
    }

    // header.h

    #include "Functions.h"

    //Global variables
    string EquationText = "";

    // To get the equation
    bool GetEquation()
    {
        // Input equation
        cout << "Answer "<<update << endl;
        cout << "---------------------" << endl;
        cout<<"Equation";
        getline(cin, EquationText);

        // Remove extra spaces in the equation
        EquationText = SpaceRemoval(EquationText);

        // Check if the equation is valid
        return EquationValidation(EquationText);
    }

    // Source 

    #include "Header.h"

    int main()
    {
        while (true)
        {
            // Get Equation
            if (GetEquation())
            {
                calculateCalc(EquationText);
                cout << "---------------------";
            }
            else
            {
                // it's a invalid equation
                cout << "invalid equation";
            }
            cin.ignore();
            system("cls");
        }

        // pause the console
        system("pause");
        return 0;
    }

我当前的输出是一个随机数,或者我想它是给我一个地址

这是所有想知道它做什么的人的完整代码

// Function.h

#include <iostream>
#include <string>
#include <cmath>
#include <cstdlib>

using namespace std;

// Assure the char is validated as a value or an expression
bool isValue(const char& c, bool countOpeningBracket, bool countClosingBracket)
{
    if (countOpeningBracket && countClosingBracket)
    {
        return c == '(' || c == ')' || c == '0' || c == '1' || c == '2' || c == '3' || c == '4' || c == '5' || c == '6' || c == '7' || c == '8' || c == '9';
    }
    else if (countOpeningBracket)
    {
        return c == '(' || c == '0' || c == '1' || c == '2' || c == '3' || c == '4' || c == '5' || c == '6' || c == '7' || c == '8' || c == '9';
    }
    else if (countClosingBracket)
    {
        return c == ')' || c == '0' || c == '1' || c == '2' || c == '3' || c == '4' || c == '5' || c == '6' || c == '7' || c == '8' || c == '9';
    }
    else
    {
        return c == '0' || c == '1' || c == '2' || c == '3' || c == '4' || c == '5' || c == '6' || c == '7' || c == '8' || c == '9';
    }
}

// Assure the character on the right side is a value or an expression
bool rightSideValidation(const string& str, const int& position)
{
    return isValue(str[position + 1], true, false);
}

// Assure the character on the left side is a value or an expression
bool leftSideValidation(const string & str, const int& position)
{
    return isValue(str[position - 1], false, true);
}

// Assure the character is a unary operator
bool isUnaryOperator(const string & str, const int& position)
{
    // it is '-' unary operator 
    if (str[position] == '-')
    {
        // if the operator is not the first in the array
        if (position > 0)
        {
            // if the previous character is not a number
            if (!leftSideValidation(str, position))
            {
                // this is unary operator e.g. 4*-6
                return true;
            }
        }
        else
        {
            // this is unary operator e.g. -6+2*8
            return true;
        }
    }

    // this is not a unary operator e.g. "4-6"
    return false;
}

// Assure the character is a valid unary operator
bool UnaryOperatorValidation(string & str, const int& position)
{
    // there is a unary operator followed by a character
    if (str.length() >= (position + 2))
    {
        // unary operator follwed by a number or an expression
        if (rightSideValidation(str, position))
        {
            // valid unary operator
            return true;
        }
    }

    // invalid unary operator
    return false;
}

// Assure the character is a binary operator
bool isBinaryOperator(const string & str, const int& position)
{
    // the character is a binary operator
    if (str[position] == '-' || str[position] == '^' || str[position] == '/' || str[position] == '*' || str[position] == '+')
    {
        return true;
    }

    // the character is NOT a binary operator
    return false;
}

// Assure the character is a valid unary operator
bool BinaryOperatorValidation(string & str, const int& position)
{
    // binary operator is between two other characters
    if (position > 0 && position < (str.length() - 1))
    {
        // the left side and the right side of the binary operator are numbers, expressions or both
        if (rightSideValidation(str, position) && leftSideValidation(str, position))
        {
            // valid binary operator. these are the four possibilities e.g. "5+6", ")+2", "7+(" or ")+(" 
            return true;
        }
    }

    // invalid binary operator
    return false;
}

// Remove a specific character from a string
void AbsoluteValueReplacement(string & str, const int& position)
{
    str.erase(position, 1);
}

// Assure the parentheses are valid in the equation
bool ParanthesesValidation(string & EquationText)
{
    int count = 0;

    // Going through the EquationText to find a '(' && ')'
    for (int i = 0; i < EquationText.length(); i++)
    {
        // an open parentheses has been found. an expression have been started
        if (EquationText[i] == '(')
        {
            count++;
        }

        // a closing parentheses has been found. an expression have been ended
        else if (EquationText[i] == ')')
        {
            if (count == 0) // invalid parentheses. an expression can't start with a closing parentheses
            {
                return false;
            }
            else // an expression have been ended
            {
                count--;
            }
        }
    }

    if (count == 0)
    {
        return true; // valid parantheses if every parentheses is closed properly
    }
    else
    {
        return false; // invalid parantheses if every parentheses is closed properly
    }
}

// Assure equation is valid
bool EquationValidation(string EquationText)
{
    // Assure the validation of paranthesses where it is part of validating the equation
    if (!ParanthesesValidation(EquationText))
    {
        return false;
    }

    // Go through EquationText to find the unary operators
    for (int i = 0; i < EquationText.length(); i++)
    {
        if (isUnaryOperator(EquationText, i)) // a unary operator was found
        {
            if (UnaryOperatorValidation(EquationText, i)) // the unary operator is valid
            {
                AbsoluteValueReplacement(EquationText, i); // remove the unary operator to ease the binary operators validation process
            }
            else
            {
                return false; // invalid unary operator was found, so it is an invalid equation
            }
        }
    }

    // Go through EquationText to find the binary operators
    for (int i = 0; i < EquationText.length(); i++)
    {
        if (isBinaryOperator(EquationText, i)) // binary operator was found in the equation
        {
            if (!BinaryOperatorValidation(EquationText, i)) // the binary operator is invalid
            {
                return false; // invalid binary operator was found, so it is an invalid equation
            }
        }
    }

    // valid equation
    return  true;
}

// Remove spaces from the equation
string  SpaceRemoval(string & EquationText)
{
    string NewEquationText = "";

    // check every character
    for (int i = 0; i < EquationText.length(); i++)
    {
        if (EquationText[i] != ' ') // if the character is not a ' ' then add it to the NewEquationText
        {
            NewEquationText += EquationText[i];
        }
    }

    // return the NewEquationText
    return NewEquationText;
}

// count the numbers and dot characters that is connected to each others and in the begining of the string
// e.g. "235*654+65" the length is 3 by counting "235"
int NumberLength(const string & str)
{
    // check all characters in the string
    for (int i = 0; i < str.length(); i++)
    {
        // if a character that is not equal to 0-9 or '.' was found, return the counter. 
        if (!(str[i] >= 48 && str[i] <= 57) && !(str[i] == '.'))
        {
            return i;
        }
    }

    // return the full length of the given string
    return str.length();
}

// Calculate expression by returning value
double CalculateExpression(string expr)
{
    // Remove extra spaces in the expression
    string xxx = SpaceRemoval(expr);

    // calculate the expression that is in-between the parentheses
    string tok = "";
    for (int i = 0; i < xxx.length(); i++)
    {
        if (xxx[i] == '(') // Parentheses was found
        {
            int iter = 1;
            string token = "";
            i++;

            // get the expression that is in-between the parentheses
            while (true)
            {
                if (xxx[i] == '(')
                {
                    iter++;
                }
                else if (xxx[i] == ')')
                {
                    iter--;
                    if (iter == 0)
                    {
                        i++;
                        break;
                    }
                }
                token += xxx[i];
                i++;
            }

            // calculate the expression that is in-between the parentheses and return the value
            tok += to_string(CalculateExpression(token));

            // remove '--'. e.g. -(-1) => --1 => 1
            for (int i = 0; i < tok.length() - 1; i++)
            {
                if (tok[i] == '-' && tok[i + 1] == '-')
                {
                    tok.erase(i, 2);
                }
            }
        }
        tok += xxx[i];
    }

    // Calculate the addition and the subtracion 
    for (int i = 0; i < tok.length(); i++)
    {
        if (tok[i] == '+')
        {
            // calculate the expressions on the right and the left by returning their summation
            return CalculateExpression(tok.substr(0, i)) + CalculateExpression(tok.substr(i + 1, tok.length() - i - 1));
        }
        else if (tok[i] == '-')
        {
            if (i == 0) // it a unary operator '-'
            {
                int numberLength = NumberLength(tok.substr(1, tok.length() - 1));

                // there is only value after the unary operator '-' e.g. "-26"
                if ((numberLength == (tok.length() - 1)) || (tok[tok.length() - 1] == '\0' && numberLength == (tok.length() - 2)))
                {
                    return -CalculateExpression(tok.substr(i + 1, numberLength));
                }
                else // there are value and expressions after the unary operator '-' e.g. "-26*8+2" "-26+8" "-26-2" "-26/2" "-8*2" "-8^4"
                {
                    int startingPosition = i + 2 + numberLength;

                    if (tok[i + 1 + numberLength] == '+')
                    {
                        // calculate the expressions on the right and the left by returning their summation
                        return -CalculateExpression(tok.substr(i + 1, numberLength)) +
                            CalculateExpression(tok.substr(startingPosition, tok.length() - startingPosition));
                    }
                    else if (tok[i + 1 + numberLength] == '-')
                    {
                        // calculate the expressions on the right and the left by returning their subtraction
                        return -CalculateExpression(tok.substr(i + 1, numberLength)) -
                            CalculateExpression(tok.substr(startingPosition, tok.length() - startingPosition));
                    }
                    else if (tok[i + 1 + numberLength] == '*')
                    {
                        // calculate the expressions on the right and the left by returning their multiplication
                        return -CalculateExpression(tok.substr(i + 1, numberLength)) *
                            CalculateExpression(tok.substr(startingPosition, tok.length() - startingPosition));
                    }
                    else if (tok[i + 1 + numberLength] == '/')
                    {
                        //  calculate the left expressions by returning its division by the right expression
                        return -CalculateExpression(tok.substr(i + 1, numberLength)) /
                            CalculateExpression(tok.substr(startingPosition, tok.length() - startingPosition));
                    }
                    else if (tok[i + 1 + numberLength] == '^')
                    {
                        // calculate the left expression by returning its power from the right expression
                        return pow(-CalculateExpression(tok.substr(i + 1, numberLength)),
                            CalculateExpression(tok.substr(startingPosition, tok.length() - startingPosition)));
                    }
                }
            }

            // calculate the expressions on the right and the left by returning their subtraction
            return CalculateExpression(tok.substr(0, i)) - CalculateExpression(tok.substr(i + 1, tok.length() - i - 1));
        }
    }

    // Calculate the power, multiplication and the division
    for (int i = 0; i < tok.length(); i++)
    {
        if (tok[i] == '^')
        {
            // calculate the left expression by returning its power from the right expression 
            return pow(CalculateExpression(tok.substr(0, i)), CalculateExpression(tok.substr(i + 1, tok.length() - i - 1)));
        }
        else if (tok[i] == '*')
        {
            // calculate the expressions on the right and the left by returning their multiplication
            return CalculateExpression(tok.substr(0, i))* CalculateExpression(tok.substr(i + 1, tok.length() - i - 1));
        }
        else if (tok[i] == '/')
        {
            //  calculate the left expressions by returning its division by the right expression
            return CalculateExpression(tok.substr(0, i)) / CalculateExpression(tok.substr(i + 1, tok.length() - i - 1));
        }
    }

    // Return the value
    return stod(tok.c_str());
}

void calculateCalc(string & EquationText)
{
    cout << "Answer " << CalculateExpression(EquationText) << endl;
}

void update(string& EquationText)
{
    string newequation = "";
     newequation = CalculateExpression(EquationText);
     cout << newequation;
}

// Header

#include "Functions.h"

//Global variables
string EquationText = "";

// To get the equation
bool GetEquation()
{
    // Input equation
    cout << "Answer ";
    update(EquationText);
    cout << endl;

    cout << "---------------------" << endl;
    getline(cin, EquationText);

    // Remove extra spaces in the equation
    EquationText = SpaceRemoval(EquationText);

    // Check if the equation is valid
    return EquationValidation(EquationText);
}

//Source
#include "Header.h"

int main()
{
    while (true)
    {
        // Get Equation
        if (GetEquation())
        {
            calculateCalc(EquationText);
            cout << "---------------------";
        }
        else
        {
            // it's a invalid equation
            cout << "invalid equation";
        }
        cin.ignore();
        system("cls");
    }

    // pause the console
    system("pause");
    return 0;
}

1 个答案:

答案 0 :(得分:0)

所以我删除了calculationcalc函数

      //  Here is my source 
 #include "Header.h"

string answer = "0";
string print = "Answer: ";
string forinvalid = "";

int main()
{
    while (true)
    {
        cout << print << answer << endl;
        cout << forinvalid;
        cout << "---------------------------\n";

        // Get Equation
        if (GetExpression())
        {
            cout << "Answer: ";
            cout << CalculateExpression(ExpressionText) << endl;
            cout << "---------------------------";
            forinvalid = "";
            answer = to_string(CalculateExpression(ExpressionText));
        }
        else
        {
            // it's a invalid equation
            cout << "invalid equation\n";
            forinvalid = "* invalid equation\n";
            print = "";
            cout << "---------------------------\n";
        }
        cin.ignore();
        system("cls");
    }

    return 0;
}

        //Header 

        #include "Functions.h"

        //Global variables
        string EquationText = "";

        // To get the equation
        bool GetEquation()
        {
            // Input equation
            getline(cin, EquationText);

            // Remove extra spaces in the equation
            EquationText = SpaceRemoval(EquationText);

            // Check if the equation is valid
            return EquationValidation(EquationText);
        }

它为我提供了所需的输出,小数点后有三个零