2017-04-25 72 views
0

op1 = c1 - '0'; op2 = c2 - '0';我想將charcter int轉換爲整型int。在C

其中C1和C2是一個字符內。讓這兩個變量1,2在字符中。 然後,我們C1具有值49,50。 從ascii碼C2值,通過該代碼,我們有值OP1 = 1; op2 = 2; 但在我的情況下,我有-47和 - 48.發生了什麼? 編輯// 對不起,冗長的代碼。我想,解決所有需要的代碼的問題。 如果我插入表達式1 + 2 + 3,那麼它將轉換爲後綴。 像(1 2 + 3 +) 和我試圖評估該後綴EXPR。 by postfix_evaluation()。此代碼後,我總是得到-42 和testcode,在1告訴我2,1和3,-45

#include <stdio.h> 
    #include <conio.h> 
    #include <ctype.h> 
    #include <string.h> 
    #define MAX 50 

    typedef struct stack 
    { 
     int data[MAX]; 
     int top; 
    }stack; 

    int precedence(char); 
    void init(stack *); 
    int empty(stack *); 
    int full(stack *); 
    int pop(stack *); 
    void push(stack *, int); 
    int top(stack *); 
    void infix_to_postfix(char infix[], char postfix[]); 
    int postfix_evaluation(char postfix[]); 

    void main() 
    { 
     char infix[30], postfix[30]; 
     int x = 0; 
     printf("expr?"); 
     gets(infix); 
     infix_to_postfix(infix,postfix); 
     x = postfix_evaluation(postfix); 

     printf("%d is a value ", x); 
     printf("postfix expr : %s", postfix); 
    } 
    int postfix_evaluation(char postfix[]) 
    { 
     int i = strlen(postfix); 
     int op1,op2,k, temp; 
     int j; 
     temp = 0; 
     stack s; 
     init(&s); 
     char opr; 
     for(j = 0; j < i; j++) 
     { 
      if(isalnum((int)postfix[j])) 
      { 
       push(&s, postfix[j]); 
       printf("%c\n", postfix[j]); 
      } 
      else 
      { 
       op1 = pop(&s) - '0'; 
       op2 = pop(&s) - '0'; 
       opr = postfix[j]; 

       switch(opr) 
       { 
       case '+': 
        printf("%d , %d \n", op1 ,op2); -- 1 
        k = op1 + op2; 
        push(&s,k); 
        break; 
       case '-': 
        push(&s,op2-op1); 
        break; 
       case '*': 
        push(&s, op1*op2); 
        break; 
       case '/': 
        push(&s, op2/op1); 
        break; 
       } 
      } 
     } 
     while(!empty(&s)) 
     { 
      temp = temp + pop(&s); 
     } 
     return temp; 

    } 
+2

你的頭腦創造了[___MCVE___(http://stackoverflow.com/help/mcve)? –

+1

[不要使用'gets()',這很危險](http://stackoverflow.com/q/1694036/2173917)。改用['fgets()'](https://linux.die.net/man/3/fgets)。 –

+0

哦對不起。當1次循環之後發生的事情。 –

回答

1

使用的atoi轉換字符爲int。

int atoi(const char *str) 

int value = atoi("90"); 
printf("Value is %d\n",value);//Value is 90 
2

有時你推一個角色,但有時你推k。當您稍後從k中彈出該值時,不應再將其轉換。

你或許應該做push(&s, postfix[j] - '0');和彈出時不轉換。

+0

我很感謝您的幫助。祝你有美好的一天。並且,我可以詢問有關在彈出時不轉換的原因嗎? –

+0

如果您同時推送轉換值和未轉換值,則在彈出時不知道要轉換哪個值。這就是爲什麼在轉換兩次後最終會以'-47'結尾。 –