C/C++の宿題を片付けます 58代目
■ このスレッドは過去ログ倉庫に格納されています
0130デフォルトの名無しさん
2006/01/19(木) 01:39:26それは環境依存な内容で、与えられた環境のコンソールを使って
標準Cを使っては実現できない。参考までに以前出した電卓をどぞ。
#include <stdio.h>
int error_code; double expr(FILE *fp); double term(FILE *fp); double fact(FILE *fp);
double expr(FILE *fp) {
double ret = term(fp); int ope;
while ((ope = fgetc(fp)) == '+' || ope == '-') if (ope == '+') ret += term(fp); else ret -= term(fp);
ungetc(ope, fp);
return ret;
}
double term(FILE *fp) {
double ret = fact(fp), temp; int ope;
while ((ope = fgetc(fp)) == '*'|| ope == '/' || ope == '%') if (ope == '*') ret *= term(fp); else if ((temp = term(fp)) != 0.) if (ope == '/') ret /= temp; else ret = (int)ret % (int)temp; else ret = error_code = 1;
ungetc(ope, fp);
return ret;
}
double fact(FILE *fp) {
double d; int parenthesis;
if (fscanf(fp, "%lf", &d) == 1) return d;
else if ((parenthesis = fgetc(fp)) =='(') {
d = expr(fp);
if ((parenthesis = fgetc(fp)) != ')') return error_code = 2; else return d;
}
else return error_code = 3;
}
int main(void) {
double d; error_code = 0; d = expr(stdin);
if (!error_code) printf("result:%lf", d);
else printf("error code:%d", error_code);
}
■ このスレッドは過去ログ倉庫に格納されています