[英]I'm trying to convert charcter int to integer int. in C
op1 = c1-'0'; op2 = c2-'0';
其中c1和c2是一個字符。 讓這兩個變量分別為1,2。 然后,我們的c1的值為49,c2的值為50。 和op2 = 2; 但就我而言,我有-47和-48。會發生什么? 編輯//對不起,我為冗長的代碼。 我認為,對於解決所有所需的代碼問題。 如果我插入一個表達式1 + 2 + 3,它將轉換為后綴。 像(1 2 + 3 +),我正在嘗試評估此后綴expr。 通過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;
}
有時您按下一個字符,但有時您按下k
。 當您稍后從k
彈出值時,不應再次轉換。
您可能應該執行push(&s, postfix[j] - '0');
並在彈出時不轉換。
使用atoi將char轉換為int。
int atoi(const char *str)
例
int value = atoi("90");
printf("Value is %d\n",value);//Value is 90
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.