2014-10-27 2 views
-2

Я пытаюсь добавить способность к возможности функции sin, pow и exp для моего калькулятора. я получаю «. Ошибки сегментации», когда я пытаюсь скомпилировать Я считаю, что проблема заключается в „ничтожной trigFunction (Char сек [])“ функцияОшибка сбоя сегментации с функциями триггера в C

#include <stdio.h> 
#include <stdlib.h> 
#include <ctype.h> 
#include <math.h> 

#define MAXOP 100 
#define NUMBER '0' 
#define TRIG 1 /**/ 
#define TRUE 1 
#define FALSE 0 

int getop(char []); 
void push(double); 
double pop(void); 
void swap(void); 
void trigFunction(char s[]); 

main() 
{ 
    int type; 
    double op2; 
    char s[MAXOP]; 

    printf("\nEnter numbers below in the following format\nwith a space between each:\n"); 
    printf("\tnum1 num2 operator\n"); 
    printf("You may use the operators:\n"); 
    printf("plus(+), minus(!), divide(/), multiply(*),\npercentage(%), swap(~), sine(S), exp(E), and pow(P)\n"); 

    while((type = getop(s)) != EOF) 
    { 
     switch(type) 
     { 
      /*other cases I have taken out to make code shorter*/ 

      case TRIG: /*case for sin, exp, pow functions*/ 
       trigFunction(s); 
       break; 


      case '\n': 
       printf("\t%.8g\n", pop());/*prints out soultion*/ 
       break; 
      default: 
       printf("error: unknown command %s\n", s); 
       break; 
     } 
    } 
    return 0; 
} 

void trigFunction(char s[]) 
{ 
    double op2; 

    if(0 == strcmp(s, 'S'))/*strcmp() function compares the string pointed to by s1 to the string pointed to by s2.*/ 
     push(sin(pop()));/*pushes the sine of pop() onto the stack*/ 
    else if(0 == strcmp(s, "E")) 
     push(exp(pop())); 
    else if(0 == strcmp(s, "P")) 
    { 
     op2 = pop(); 
     push(pow(pop(), op2)); 
    } 
    else 
     printf("I don't know what you mean by %s, but I may \nself destruct if you don't enter   \na correct operator\n", s); 
} 

#define MAXVAL 100 

int sp = 0; 
double val[MAXVAL]; 

void push (double f) 
{ 
    if(sp < MAXVAL) 
    { 
     val[sp++] = f; 
    } 
    else 
    { 
     printf("error: stack full, cant push %g\n",f); 
    } 
} 

double pop(void) 
{ 
    if(sp > 0) 
    { 
     return val[--sp]; 
    } 
    else 
    { 
     printf("error: stack empty \n"); 
     return 0.0; 
    } 
} 

int getch(void); 
void ungetch(int); 

int getop(char s[]) 
{ 
    int i = 0, c, next; 

    while ((s[0] = c = getch()) == ' ' || c == '\t')/*skips white space*/ 
    ; 
    s[1] = '\0'; 

    if(isalpha(c)) 
    { 
     i = 0; 
     while(isalpha(s[i++] = c)) 
     c = getch();  
     s[i - 1] = '\0'; 
     if(c != EOF) 
     /*ungetch(c);*/ 
     return TRIG; 
    } 

    if(!isdigit(c) && c != '.' && c != '-')/* not number. may contain minus*/ 
    return c; 
    if(c == '-') 
    { 
    next = getch(); 
    if(!isdigit(next) && next != '.') 
    { 
     ungetch(next);/*puts next char in buffer*/ 
     return c; 
    }  
    c = next; 
    } 
    else 
    c = getch(); 

    while(isdigit(s[++i] = c)) 
      c = getch(); 
    if(c == '.')      /* Collect fraction part */ 
     while(isdigit(s[++i] = c = getch())) 
         ; 
    s[i] = '\0'; 
    if(c != EOF) 
     ungetch(c);/*puts c in buffer*/ 
    return NUMBER; 
} 

#define BUFSIZE 100 

char buf[BUFSIZE]; 
int bufp = 0; 

int getch(void) 
{ 
    return(bufp > 0) ? buf[--bufp] : getchar(); 
} 

void ungetch(int c) 
{ 
    if(bufp >= BUFSIZE) 
    { 
     printf("unGetch: too many characters\n"); 
    } 
    else 
    { 
     buf[bufp++] = c; 
    } 
} 
+6

использовать отладчик, чтобы точно определить ошибочную инструкцию. также, измените 'if (0 == strcmp (s, 'S'))' to 'if (0 == strcmp (s," S "))'. Научитесь предоставлять [MCVE] (http://stackoverflow.com/help/mcve) –

+0

Попробуйте включить предупреждения в компилятор. Ошибка, которую Сурав рассказал вам, должна была найти компилятор. – gnasher729

ответ

0
void trigFunction(char s[]) 
{ 
    double op2; 

    if(0 == strcmp(s, 'S'))/*strcmp() function compares the string pointed to by s1 to the string pointed to by s2.*/ 
     push(sin(pop()));/*pushes the sine of pop() onto the stack*/ 
    else if(0 == strcmp(s, "E")) 
     push(exp(pop())); 
    else if(0 == strcmp(s, "P")) 
    { 
     op2 = pop(); 
     push(pow(pop(), op2)); 
    } 
    else 
     printf("I don't know what you mean by %s, but I may \nself destruct if you don't enter   \na correct operator\n", s); 
} 

Ну, давайте посмотрим:

if(0 == strcmp(s, 'S')) 

должен быть

if(0 == strcmp(s, "S")) 

, как вы передаете один char в функцию, ожидающую char * ...

Это должно исправить ваш код.

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

if (s[0] = 'S') 

и сравните char к char, хотя это не поможет, если вы хотите расширить его позже, например, используя as для arcsine.

Sidenote:
Интересно знать, что три основные тригонометрические функции
sin, exp и pow. Я делал это неправильно в течение многих лет сsin, cos и tan.
(Я предполагаю, что они просто заполнители)

Смежные вопросы