-
-
Save castaneai/10577635 to your computer and use it in GitHub Desktop.
逆ポーランド記法
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
int stack_head = 0; | |
int stack[100]; | |
/** | |
* 四則演算に使う演算子 | |
*/ | |
typedef enum | |
{ | |
ADD = '+', // 足し算 | |
SUBTRACT = '-', // 引き算 | |
MULTIPLY = '*', // 掛け算 | |
DIVIDE = '/' // 割り算 | |
} Operator; | |
/** | |
* スタックに新しい数値を入れる | |
*/ | |
void push(int value) | |
{ | |
stack[stack_head] = value; | |
stack_head++; | |
} | |
/** | |
* スタックから1つの数値を取り出す | |
*/ | |
int pop() | |
{ | |
stack_head--; | |
return stack[stack_head]; | |
} | |
/** | |
* 指定した文字列が演算子であるかどうか調べる | |
* | |
* @param input 指定する文字列 | |
*/ | |
int is_operator(char* input) | |
{ | |
return input[0] == ADD || | |
input[0] == SUBTRACT || | |
input[0] == MULTIPLY || | |
input[0] == DIVIDE; | |
} | |
/** | |
* 四則演算をする | |
* | |
* @param left 左辺 | |
* @param right 右辺 | |
* @param ope 演算子 | |
* @return 四則演算の結果 | |
*/ | |
int calc(int left, int right, Operator ope) | |
{ | |
switch (ope) { | |
case ADD: | |
return left + right; | |
case SUBTRACT: | |
return left - right; | |
case MULTIPLY: | |
return left * right; | |
case DIVIDE: | |
return left / right; | |
default: | |
printf("calculation error. invalid operator.\n"); | |
return 0; | |
} | |
} | |
int main(int argc, char* argv[]) | |
{ | |
int i; | |
for (i = 1; i < argc; i++){ | |
char* input = argv[i]; | |
if (is_operator(input)) { | |
int right = pop(); | |
int left = pop(); | |
push(calc(left, right, input[0])); | |
} | |
else { | |
push(atoi(input)); | |
} | |
} | |
int answer = pop(); | |
printf("演算結果は%dです\n", answer); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment