用C语言做计算器,白嫖党们点进来

  1. 标题

做一个计算器,C语言版本的,拿去吧哈哈

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
/*  从字符串中一个指定的地址,提取出一个浮点数,存入pnum参数指向的内存中,并返回所处理字符的个数  如果未提取出浮点数(无数字字符),则返回一个负数,绝对值表示已处理字符个数*/
int getoperand(const char *str,double *pnum){	  int i = 0,j = 0;	
     char *p = str;	
    char buf[20] = { 0 };
  	if (str == NULL || pnum == NULL)	
  		return 0;		
  		while (isspace(*p))/*去除前面的空白字符*/	{	
  			++i;		
  			++p;	
  			}
	/*		C 标准库 <ctype.h>	isdigit(一个字符)函数检查字符是否为数字字符(0-9)。	返回非零 是数字	零 非数字 		*/ 
		if (isdigit(*p))	{
		while (isdigit(*p) || *p == '.')		
		buf[j++] = *p++;	
		buf[j] = '\0';		
		/*		   函数名: atof		   C 标准库 - <stdlib.h>          功  能: 把字符串转换成浮点数          用  法: double atof(const char *nptr); 		*/ 		    
		*pnum = atof(buf); 		
		return i + j;	
		}	else		
		return -i;}
		/*  对运算数数组和运算符数组进行计算  operand:运算数,op:运算符 ,n运算符的个数   返回:运算结果*/
		double eval(double *operand, char *op, int n){
			double val = 0;//val保存每一次计算结果
		 	int i;
		 	if (operand == NULL || op == NULL)		           return 0;
		 		val = operand[0];//将第一个运算数赋值给val 
		 		for (i = 0; i < n; i++)	{	
		 			switch (op[i])		{	
		 				case '+':	val += operand[i + 1];	break;	
		 				case '-':			val -= operand[i + 1];	break;	
		 				case '*':			val *= operand[i + 1];		break;	
		 				case '/':			val /= operand[i + 1];	break;		
		 				default:			break;		
		 				}	
		 				}	
		 				return val;
		 				}
		/*  计算字符串的值  12+23/45*30-34   返回:计算结果*/
		double cal_v4(const char *str){	
		double val = 0;	
		double operand[20] = { 0 };//保存操作数 1 1.2 0.2  
			int m = 0;	
			char op[20] = { 0 };//保存操作符号 + - * /
			int n = 0;	double dtmp;//当前操作数 	int j = 0;
		   char *p;
		   for (p = str; *p; p++)	{
		   		/*如果是数字字符,则提取出一个运算数,存放到运算数数组*/	
		   	if (isdigit(*p))		{		
		   		j = getoperand(p, &dtmp);		
		   		operand[m++] = dtmp;	
		   		p = p + j - 1;//移动指针到下一个操作符号 
		   				}	
		   		/*		  如果是乘号(或除号),则提取出后一个运算数,并于运算数数组中最后一个元素进行乘(除)运算,		  运算结果再保存回运算数数组		*/	
          	else if (*p == '*')		{			j = getoperand(p + 1, &dtmp);		
          	operand[m - 1] = operand[m - 1] * dtmp;	
          			p += j;	
          				}	
          	else if (*p == '/')		{	
          		j = getoperand(p + 1, &dtmp);			          operand[m - 1] = operand[m - 1] / dtmp;			        p += j;		
          		}	
         	else if (*p == '+' || *p == '-' || *p == '*' || *p == '/')		{		
         		op[n++] = *p;
         				}	
         				}	
         	return eval(operand, op, n);
         	}
 int main(void){	
       char buf[256] = { 0 };
       	printf(">");	
       	while (strcmp(fgets(buf, 256, stdin), "quit\n") != 0)	{	
       	printf("%s=%f\n",buf, cal_v4(buf));		   printf(">");	}	return 0;
       	}

总结

总结,这是我们老师要求做的一个作业。嘿嘿,可能从编辑器代码复制过来有问题,这是正常情况,你们自己可以稍微调整一下,应该能行。
至于这篇文章,巩固一下自己的知识。从编程计算器开始,我打开了编程的大门,C语言这条路还有很长的一段路要走。
送句话,道途艰阻,仍需负重前行!
我们一起学习!!

posted @ 2021-04-17 17:40  辰梦starDream  阅读(2)  评论(0编辑  收藏  举报  来源