2014-02-20 43 views
0

你好我试图做一个计算器,用户把运动(成一个字符串),并转移到乘法除加法和减法的四个功能我的功能已准备就绪,但我有两个主要问题,我需要你的帮助。使计算器使用C语言

所以这是我的第一个问题是,当我把我的函数(char函数)我的程序崩溃,但是当我运行相同的函数(在主函数中)它没有问题。所以我很想知道为什么发生这种情况以及我如何解决它。

第二个问题是我如何使所有功能使自己多次(递归),所以如果你能帮助我做一个函数来做到这一点,我很感激它。

另一个小问题,我会很高兴,如果你能帮助我,并使该函数返回(返回)原始字符串到下一个函数。

我的代码 -

#include <stdio.h> 
#include <string.h> 

char multiplication(char str[]); 

int main() 
{ 
    char str[99] = "3-5+5*7"; 
    multiplication(str); 
    return(0); 
} 

char multiplication(char str[]) 
{ 
    char strp[99]; 
    char str1[99] = {0}; 
    char str2[99]; 
    char mul[99] = "*"; 
    char old[99]; 
    char *rev; 
    int i, k, j = 0, aPos, zPos, len; 
    int sum,sum1,sum2; 
    static char buffer[4096]; 
    char *p; 

    len = strlen(str); 
    strcpy (strp, str); 
    aPos = zPos = -1; 

    for(i =0; i<len; i++) 
    { 
     if(str[i] == '+') 
     { 
      aPos = i; 
     } 
     else if(str[i] == '*')  
     { 
      zPos = i; 
      break; 
     } 
    } 

    if(aPos != -1 && zPos != -1) 
    { 
     for(k=0, i=zPos-1;i>aPos;--i,++k) 
     { 
      str1[k]=str[i]; 
     } 
    } 

    rev = strrev(str1); 

    for(i = 0; i<10; i++) 
    { 
     if(strp[i] == '*') 
     { 
      while(strp[i+1] != '+' || '\0') 
      { 
       str2[j++] = strp[++i]; 
      } 
     } 
    } 

    old[0] = '\0'; 
    strcat(old,str1); 
    strcat(old,mul); 
    strcat(old,str2); 

    sum1 = atoi (str1); 
    sum2 = atoi (str2); 
    sum = sum1 * sum2; 

    str2[j] = '\0'; 
    sprintf(str2,"%d",sum); 

    if(!(p = strstr(str, old))) 
     printf("%s",str); 
    strncpy(buffer, str, p-str); // Copy characters from 'str' to the new string 
    buffer[p-str] = '\0'; 
    sprintf(buffer+(p-str), "%s%s", str2, p+strlen(old)); 
    printf("%s",buffer); 
} 

由于任何人谁可以帮助我,我非常感激

+0

至于解决,你的一般方法应该是把你的字符串和分裂成字符。然后,您可以使用[Shunting-Yard Algorithim](http://en.wikipedia.org/wiki/Shunting-yard_algorithm)将该公式转换为RPN。我已经实现了这个算法,它的工作非常出色。 – StephenH

+0

你能给我一个这个解决方案的练习的例子吗? – user3332897

+0

请参阅http://stackoverflow.com/a/21800127我认为这会有所帮助。 – BLUEPIXY

回答

0

最好的方法对于一般这个问题将它转换infix notationReverse Polish NotationShunting Yard Algorithim。我想你会发现this blog有助于理解分流码算法的一些实现来创建这种解算器。我还推荐阅读shunting yard algorithmRPN上的维基百科页面。

通过这些资源,您可以发现将infix notation转换为RPN的最有效方式是使用shunting yard algorithm。然后在代码中评估你的RPN等式(使用堆栈数据结构...继续阅读)是微不足道的。为了完成所有这些,我建议您在C/C++检查this implementation of a stack at cprogramming.comthis implementation from the cs department at MITthis implementation from the cs department at Boston University中了解stack data structure及其实现。

cprogramming.com reference更多的是C++实现,因为它使用了模板。如果你只是想要代码,请查看link from MIT