| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 813 人关注过本帖
标题:c语言计算器问题
只看楼主 加入收藏
captain2050
Rank: 2
等 级:论坛游民
帖 子:57
专家分:43
注 册:2016-7-15
结帖率:92.86%
收藏
 问题点数:0 回复次数:0 
c语言计算器问题
可以实现加减乘除,如果以=开头,就引用上一个式子的计算结果,不考虑优先级(就是从左到右算1+2*4=12)
但就是 以=开头 总是计算不对 哪里有错?谢谢
(注:setbuf在linux里用来清空缓冲区)
程序代码:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>

int main()
{
  double result=0.0;  //calculation result
  char* buf=malloc(30*sizeof(char));   //input buffer
  int len;       //length of buffer
  char* p_buf=NULL ;    //point to buffer
  double num[100];    //store the operand
  char operator[100];  //store the operator

  while(1)
    {
      //the process of input
      setbuf(stdin,NULL);
      p_buf=fgets(buf,30,stdin);
      if(!p_buf)
    {
      printf("input error\n");
      return 0;
    }
      if(strcmp(buf,"quit\n")==0)
    return 0;
      len=strlen(buf);
      buf[len-1]='\0';

      //delete space
      for(int old=0,new=0;old<len;old++)
    {
      if(buf[old]!=' ')
        buf[new++]=buf[old];
    }
      len=strlen(buf);

      //identify the result
      if(*buf=='=')
    num[0]=result;
      else
    {
      result=num[0]=0;
      operator[0]='+';
    }

      //extract numbers
      char new_buf[100];
      strcpy(new_buf,buf);
      char* p_num=strtok(buf,"-+*/^");
      double each_num;
      int new=1;
      while(p_num!=NULL)
    {
      each_num=atof(p_num);
      num[new++]=each_num;
      p_num=strtok(NULL,"-+*/^");
    }
      int how_many_num=new;
     

      //extract operators
      if(*new_buf=='=')
    {
      new=0;
      num[0]=result;
    }
      else
    {
      new=1;
      result=num[0]=0;
      operator[0]='+';
    }
      char* p_char=strtok(new_buf,"=1234567890");
      while(p_char!=NULL)
    {
      operator[new++]=*p_char;
      p_char=strtok(NULL,"=1234567890");
    }
      int how_many_operator=new;

      result=num[0];
      int i=0,j=1;
      for(;i<how_many_operator;i++)
    {
      switch (operator[i])
        {
        case '+': result+=num[j];break;
        case '-': result-=num[j];break;
        case '*': result*=num[j];break;
        case '/': result/=num[j];break;
        }
      j++;
    }
      printf("result=%f\n",result);
    }
}

搜索更多相关主题的帖子: int result char num new 
2017-07-27 13:19
快速回复:c语言计算器问题
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.016026 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved