c计算数学表达式

/*
 ============================================================================
 Name        : demo.c
 Author      : Johnson Z.
 Version     :
 Copyright   : Your copyright notice
 Description : Hello World in C, Ansi-style
 ============================================================================
 */

#include 
#include 

struct node {
	double radix;
	char operator;
	struct node* next;
};

int npower(int n) {
	int val = 1;
	if (n == 0) return 1;
	while (n-- > 0)
		val *= 10;
	return val;
}

double get_value(char* str, int len) {
	double val = 0;
	char c = *str;
	len--;
	while (c != 0) {
		int i = c - 48; // '0' == 48
		val += i * npower(len--);
		str++;
		c = *str;
	}

	return val;
}

void compute(char* input) {
	printf("input=%s\n", input);
	struct node* head = NULL;
	struct node* ptr = NULL;
	struct node* pre = NULL;
	char* buf = (char*) calloc(1, 13);

	for (char c = *input; c != 0; c = *input) {
		pre = ptr;
		ptr = (struct node*) calloc(1, sizeof(struct node));
		ptr->operator = 0;
		ptr->next = NULL;

		if (NULL != pre) {
			pre->next = ptr;
		}

		if (NULL == head) {
			head = ptr;
		}

		if (c == '+' || c == '-' || c == '*' || c == '/') {
			ptr->operator = c;
			input++;
			continue;
		}

		int idx = 0;
		while (c != '+' && c != '-' && c != '*' && c != '/' && c != 0) {
			buf[idx++] = c;
			input++;
			c = *input;
		}
		buf[idx] = 0;

		ptr->radix = get_value(buf, idx);
	}

	pre = head;
	ptr = pre->next;
	while (ptr != NULL ) {
		if (ptr->operator && ptr->operator != '+' && ptr->operator != '-') {
			if (ptr->operator == '*') {
				pre->radix = (pre->radix) * (ptr->next->radix);
			}

			if (ptr->operator == '/') {
				pre->radix = pre->radix / ptr->next->radix;
			}

			pre->next = ptr->next->next;
			pre->operator = 0;
			ptr = pre->next;
			continue;
		}
		pre = ptr;
		ptr = ptr->next;
	}

	pre = head;
	ptr = pre->next;
	while (ptr != NULL ) {
		if (ptr->operator && ptr->operator != '*' && ptr->operator != '/') {
			if (ptr->operator == '+') {
				pre->radix = (pre->radix) + (ptr->next->radix);
			}

			if (ptr->operator == '-') {
				pre->radix = pre->radix - ptr->next->radix;
			}

			pre->next = ptr->next->next;
			pre->operator = 0;
			ptr = pre->next;
			continue;
		}
		pre = ptr;
		ptr = ptr->next;
	}

	printf("value=%.2f\n", pre->radix);

	ptr = head;
	while (ptr) {
		pre = ptr;
		ptr = ptr->next;
		free(pre);
	}
	free(buf);
}

int main(void) {
	compute("100/2-200/2+100*1+200*1-10/3");
	return EXIT_SUCCESS;
}



你可能感兴趣的:(Linux)