[ create a new paste ] login | about

Link: http://codepad.org/n47BkpXa    [ raw code | output | fork ]

C, pasted on Jul 21:
#include <stdio.h>
#include <stdlib.h>

int calc(int *x, char *op, int mode)  				/* x=項、op=演算子、mode=0か1で処理を分岐*/
{
	while (*op != '=') {							/*opに'='が代入されるまで回す*/
		if (mode==0) {								/*mode=0の処理(mode=1で得た計算結果を最後に加算する)*/
			*(x + 1) = *(x+1) + (*x);				
			x++;									/*配列に入れられた値を更新*/
			op++;									/*'='が出されるまでopを更新*/
		}
    	if (mode==1) {								/*mode=1の処理(乗算、除算、減算を行って、計算結果を配列に入れる)*/
			switch (*op) { 
	  		/*乗算*/
	  		case '*':				
        		*(x + 1) = (*x) * (*(x+1));			/*例:x+1=4(x)×2(x+1)*/
        		*x = 0;
        		break;
      		/*除算*/
	  		case '/':				
        		*(x + 1) = *x / *(x + 1);			/*例:x+1=4(x)÷2(x+1)*/
        		*x = 0;
        		break;
      		/*減算*/
	  		case '-':								/*例:x+1=2×(-1)*/
				*(x + 1) = *(x+1) * (-1);			/*最後に加算を行うので値をマイナスにして配列に入れる*/ 
        		break;
		}
		x++;
		op++;
		}
	}
	return *x;
}

int	main(void)
{
  double          x[10];							/* 項 */
  char            op[10];							/* 演算子 */
  int             i;
  while (1) {
    printf("式を入力してください\n");
	printf("例:1*2+5=enter \n");
    printf("式:");
    for (i = 0; i<10; i++) {						/*10項まで計算可*/
      scanf("%d %c", x + i, op + i);
      if (*(op + i) == '=')							/*op='='が代入されるまでmode=1の処理へ移行*/
		break;
	}
    calc(x, op, 1);									/*mode=1の処理へ移行(乗算、除算、減算の処理)*/
    printf("答え:%d\n", calc(x, op, 0));			/*mode=0の処理へ移行(最後に加算をして結果を出力)*/
  }
  return 0;
}


Output:
1
Segmentation fault


Create a new paste based on this one


Comments: