Полиномиальный калькулятор - PullRequest
0 голосов
/ 09 марта 2010

Я делаю полиномиальный калькулятор, и мне понадобится помощь, так как я буду совершенствовать код.

Пока я создал только класс polinom, который я представлял в виде связанного списка с терминами и некоторыми функциями (пока только читайте и печатайте полиномиальные функции).

Вот основная программа, которая пока только читает полином и печатает его:

#include "polinom.h"

int main()

{

polinom P1;
bool varStatus = false;
char var = '\0', readStatus = '\0';

cout << "P1 = ";
P1.read(readStatus, var, varStatus); // i don't need readStatus yet as i haven't implemented the reset and quit functions 

cout << "\n\nP = ";
P1.print(var);

getch();
return 0;
}

И заголовочный файл polinom.h:

#ifndef _polinom_h
#define _polinom_h

#include <iostream>
#include <list>
#include <cstdlib>
#include <cctype>
#include <cstdio>
#include <conio.h>


using namespace std;

class polinom 
{
class term
{
    public:
        int coef;
        int pow;

        term() 
        {
            coef = 1;
            pow = 0;
        }    
};

list<term> poly;
list<term>::iterator i;

public:

    bool printable(char c) 
    {

        return (
                  ((int(c) > 42 && int(c) < 123) || isspace(c)) && int(c) != 44 && int(c) != 46 && int(c) != 47 && 
                  int(c) != 58 && int(c) != 59 && 
                  int(c) != 60 && int(c) != 61 && int(c) != 62 && int(c) != 63 && int(c) != 64 && int(c) != 65 && 
                  int(c) != 91 && int(c) != 92 && int(c) != 93 && int(c) != 95 && int(c) != 96
                ); 
    }


    void read(char &readStatus, char &var, bool &varStatus)
    {

        term t; // term variable to push it into the list of terms
        char c, lc, sign; // c = current char, lc = lastchar and sign the '+' or '-' sign before a coefficient
        int coef, pow; //variables to pass the coef and power to term t
        bool coefRead = false, powRead = false; //reading status of coef and power 

        while (c != '\r') { //we read characters until carriage return
            c = getch(); // get the new imputed char

            if (tolower(c) == 'r' || tolower(c) == 'q') { //if the user inputed r or q we reset the input or quit the program
                    readStatus = c; //pass current char value to readStatus so the program will know what to do next
                    return; //aborting the reading process
            }

            else 
            {
                if (printable(c)) cout << c; //print on screen only the correct characters

                if (!coefRead && !powRead) //we set term coef to the inputed value
                {                    
                    if (isdigit(c)) { 
                        if (isdigit(lc)) coef = coef * 10 + int(c); //if the last char was also a digit we multiply the last value of coef by 10 and add current char
                        else {                                    
                            if (sign == '-')  coef = -(int(c));//if the current coef has '-' before we set coef to it's negative value 
                            else              coef = int(c);   //this means a new term's coef is read
                    }
                    if (!isdigit(c) && isdigit(lc)) coefRead = true; //if the last char was a digit and we reached the var name we stop reading the coefficient
                }

                else if (coefRead && !powRead) //after coefficient is read we get the term's varname and power 
                {
                    if (isdigit(c)) { // just like in the case with coefficient we read the power until the current char is not a digit
                        if (isdigit(lc)) pow = pow * 10 + int(c);
                        else pow = int(c);
                    }

                    else if (isalpha(c) && isdigit(lc) && !varStatus) { //if the last char was a digit and the current not we reached the var name
                    var = c;                                            //also even though the variable is inputed more than once we save it only once
                    varStatus = true; //we mark the var name as read
                    }
                    else {
                        if (isdigit(lc)) powRead = true;
                    }   
                }

            else {
                if (c == '+' || c == '-') { // if a sign was inputed it means a new term is coming and we push the current term to the list and reset 
                    t.coef = coef;          // coefRead and powRead so we can read another term 
                    t.pow = pow;
                    poly.push_back(t);
                    sign = c;
                    coefRead = false;
                    powRead = false;
                }
            }

           lc = c; // we save the last character

            }
        } 
    }

    void print(char var)
    {
        for ( i=poly.begin() ; i != poly.end(); i++ ) { //going through the entire list to retrieve the terms and print them 

            if (i == poly.end() - 1) { // if we reached the last term 
                if (*(i->pow == 0) //if the last term's power is 0 we print only it's coefficient
                    cout << *(i->coef);
                else 
                    cout << *(i->coef) << var << "^" << *(i->pow); //otherwise we print both
            }

            else {
                if (*(i->coef > 0) //if the coef value is positive 
                    cout << *(i->coef) << var << "^" << *(i->pow) << " + "; //we also add the '+' sign
                else 
                    cout << *(i->coef) << var << "^" << *(i->pow) << " - "; // otherwise we add '-' sign
            }
        }
    }

};


#endif                    

EDIT

Все ошибки компиляции теперь исправлены благодаря JonH, но функция чтения не работает, так как вводимые символы не правильно вставлены в список. Я знаю, что это может быть тривиально для вас, ребята, но было бы здорово, если бы вы мне помогли.

Спасибо!

Ответы [ 4 ]

10 голосов
/ 10 марта 2010

Я обнаружил МНОГИЕ пропущенные фигурные скобки и закрывающие скобки по всему вашему коду. Потратив несколько минут на исправление по крайней мере 10 из них, я подумал, что вам будет лучше, если я помогу вам научиться ловить рыбу, а не давать вам рыбу на ужин сегодня вечером.

Ваш код написан как поток сознания. По мере того, как вы создаете свой код, ваш разум прыгает, думая о других вещах, которые вам нужно создать, и о новых требованиях, которые вы вводите в то, что только что написали. Когда вы думаете об этих вещах, вы пишете их и возвращаетесь туда, где вы были. Прежде чем вы это знаете, вы написали сотни строк кода, перепрыгивая, записывая биты здесь и там. Проблема в том, что вы не можете продолжать жонглировать фрагментами кода, не пропуская при этом небольшие синтаксические биты.

Вы должны использовать более итеративный подход к написанию кода. Как именно вы это сделаете, придет с опытом, но вот несколько советов:

  1. Начните с того, что заглушите объявление класса несколькими (желательно 1) основными методами и переменными-членами.
  2. Compile. Вы получите ошибки компоновщика и тому подобное, но вы не должны получать никаких синтаксических ошибок, таких как пропущенные скобки или точки с запятой. Исправьте все, что вы найдете, прежде чем двигаться дальше.
  3. Реализуйте методы, которые вы только что оформили. Компиляция и исправление ошибок некомпоновщика.
  4. Когда вы думаете о второстепенных или зависимых требованиях, которые возникли на предыдущих этапах, напишите комментарии в своем коде, например // TODO: Implement bool DoTheThing(int); Но пока не реализуйте их.
  5. Вернитесь к шагу 1, чтобы сфера действия, над которой вы работаете, была как можно более ограниченной и фундаментальной. Никогда не выходите за пределы этапа компиляции без чистой компиляции.

Повторяйте, пока все не будет реализовано. Вы можете скомпилировать 50 или более раз за этот процесс.

2 голосов
/ 09 марта 2010

Ваша основная проблема в том, что вы написали кучу кода, не тестируя его по частям, не думая об этом. Когда вы пишете как новичок, вы должны попытаться добавить по одному поочередно и убедиться, что он компилируется. Даже будучи опытным программистом, модульность является чрезвычайно важной частью процесса проектирования и написания кода.

Тем не менее, вот несколько советов о вашем размещенном коде, в частности:

  1. Ваша функция printable безобразна как грех, и поэтому ее невозможно отладить или понять.
  2. Количество вложенных if операторов указывает на недостатки дизайна.
  3. В вашем выражении if (isdigit(c)) отсутствует пропущенная скобка.
  4. Объявление (и особенно инициализация) нескольких переменных в одной строке является неправильной формой.
1 голос
/ 09 марта 2010

Вам не хватает нескольких фигурных скобок в функции чтения.

Я переделал это здесь:

 void read(char &readStatus, char &var, bool &varStatus) 
{ 

    term t; // term variable to push it into the list of terms 
    char c, lc, sign; // c = current char, lc = lastchar and sign the '+' or '-' sign before a coefficient 
    int coef, pow; //variables to pass the coef and power to term t 
    bool coefRead = false, powRead = false; //reading status of coef and power  

    while (c != '\r') { //we read characters until carriage return 
        c = getch(); // get the new imputed char 

        if (tolower(c) == 'r' || tolower(c) == 'q') 
        { //if the user inputed r or q we reset the input or quit the program 
                readStatus = c; //pass current char value to readStatus so the program will know what to do next 
                return; //aborting the reading process 
        } 

        else  
        { 
            if (printable(c)) 
               cout << c; //print on screen only the correct characters 

            if (!coefRead && !powRead) //we set term coef to the inputed value 
            {                     
                if (isdigit(c)) 
                   {  
                    if (isdigit(lc)) 
                       coef = coef * 10 + int(c); //if the last char was also a digit we multiply the last value of coef by 10 and add current char 
                    else 
                      {                                     
                        if (sign == '-')  
                           coef = -(int(c));//if the current coef has '-' before we set coef to it's negative value  
                        else              
                           coef = int(c);   //this means a new term's coef is read 
                      } //end else 
                    }//end if isdigit(c)
                if (!isdigit(c) && isdigit(lc)) 
                   coefRead = true; //if the last char was a digit and we reached the var name we stop reading the coefficient 
            }  //end if

            else if (coefRead && !powRead) //after coefficient is read we get the term's varname and power  
            { 
                if (isdigit(c)) 
                   { // just like in the case with coefficient we read the power until the current char is not a digit 
                    if (isdigit(lc)) 
                       pow = pow * 10 + int(c); 
                    else 
                         pow = int(c); 
                    } 

                else if (isalpha(c) && isdigit(lc) && !varStatus) 
                     { //if the last char was a digit and the current not we reached the var name 
                         var = c;                                            //also even though the variable is inputed more than once we save it only once 
                          varStatus = true; //we mark the var name as read 
                     } 
                else 
                     { 
                     if (isdigit(lc)) 
                        powRead = true; 
                     }    
            } //end else if 

        else 
             { 
             if (c == '+' || c == '-') 
                { // if a sign was inputed it means a new term is coming and we push the current term to the list and reset  
                  t.coef = coef;          // coefRead and powRead so we can read another term  
                  t.pow = pow; 
                  poly.push_back(t); 
                  sign = c; 
                  coefRead = false; 
                  powRead = false; 
                } 
              } 

       lc = c; // we save the last character 

        } //end else
    }  //end while
} //end function

EDIT

Я также исправил функцию печати:

 void print(char var) 
    { 
        for ( i=poly.begin() ; i != poly.end(); i++ ) { //going through the entire list to retrieve the terms and print them  

            if (i == poly.end()) { // if we reached the last term  
                if (i->pow == 0) //if the last term's power is 0 we print only it's coefficient 
                    cout << i->coef;
                else  
                    cout << i->coef << var << "^" << i->pow; //otherwise we print both 
            } 

            else { 
                if (i->coef > 0) //if the coef value is positive  
                    cout << i->coef << var << "^" << i->pow << " + "; //we also add the '+' sign 
                else  
                    cout << i->coef << var << "^" << i->pow << " - "; // otherwise we add '-' sign 
            } 
        } 
    } 
1 голос
/ 09 марта 2010

У этих ошибок компиляции обязательно есть номер строки, связанный с ними в сообщении об ошибке. Вы пробовали смотреть на указанную строку, чтобы увидеть, чего не хватает? Если это не поможет, пожалуйста, опубликуйте полный вывод ошибок от компилятора, чтобы мы могли определить, что это за ошибка.

...