能计算加减乘除表达式,求添加计算平方、三角函数的功能,在线等,急

杜小牙 2015-06-16 07:56:00
各位C语言大神,求帮忙,现在代码能计算加减乘除表达式,但是不能计算平方和三角函数,求大神添加功能。
在线等~~~

// EX6_08.CPP
// A program to implement a calculator

#include <stdio.h> // For input/output
#include <stdlib.h> // For the exit() function
#include <ctype.h> // For the isdigit() function
#include <string.h> // For the strcpy() function

void eatspaces(char * str); // Function to eliminate blanks
double expr(char * str); // Function evaluating an expression
double term(char * str, int * pindex); // Function analyzing a term
double number(char * str, int * pindex); // Function to recognize a number
char * extract(char * str, int * index); // Function to extract a substring

const int MAX = 80; // Maximum expression length including '\0'

int main(void)
{
char buffer[MAX]; // Input area for expression to be evaluated
char c;
int i;

printf("Welcome to your friendly calculator.\n");
printf("Enter an expression, or an empty line to quit.\n");

for(;;)
{
i=0;
scanf("%c",&c); // Read an input line
while(c!='\n')
{
buffer[i++]=c;
scanf("%c",&c);


}
buffer[i]='\0';

eatspaces(buffer); // Remove blanks from input

if(!buffer[0]) // Empty line ends calculator
return 0;

printf( "\t= %f\n\n",expr(buffer)); // Output value of expression
}

}


// Function to eliminate blanks from a string
void eatspaces(char * str)
{
int i=0; // 'Copy to' index to string
int j=0; // 'Copy from' index to string

while((*(str+i) = *(str+j++)) != '\0') // Loop while character copied is not \0
if(*(str+i) != ' ') // Increment i as long as
i++; // character is not a blank
return;
}


// Function to evaluate an arithmetic expression
double expr(char * str)
{
double value = 0; // Store result here
int index = 0; // Keeps track of current character position

value = term(str, &index); // Get first term

for(;;) // Infinite loop, all exits inside
{
switch(*(str+index++)) // Choose action based on current character
{
case '\0': // We're at the end of the string
return value; // so return what we have got

case '+': // + found so add in the
value += term(str, &index); // next term
break;

case '-': // - found so subtract
value -= term(str, &index); // the next term
break;

default: // If we reach here the string
printf("Arrrgh!*#!! There's an error.\n");
exit(1);
}
}
}


// Function to get the value of a term
double term(char * str, int * pindex)
{
double value = 0; // Somewhere to accumulate the result

value = number(str, pindex); // Get the first number in the term

// Loop as long as we have a good operator
while((*(str+(*pindex))=='*')||(*(str+(*pindex))=='/'))
{

if(*(str+(*pindex))=='*') // If it's multiply,
{
++(*pindex);
value *= number(str, pindex); // multiply by next number
}

if(*(str+(*pindex))=='/') // If it's divide,
{
++(*pindex);
value /= number(str, pindex); // divide by next number
}
}
return value; // We've finished, so return what we've got
}


// Function to recognize a number in a string
double number(char * str, int * pindex)
{
double value = 0.0; // Store the resulting value

char * psubstr; // Pointer for substring
if(*(str + (*pindex)) == '(') // Start of parentheses
{
++(*pindex);
psubstr = extract(str, pindex); // Extract substring in brackets
value = expr(psubstr); // Get the value of the substring
return value; // Return substring value
}

while(isdigit(*(str+(*pindex)))) // Loop accumulating leading digits
value=10*value + (*(str+(*pindex)++) - 48);

// Not a digit when we get to here

if(*(str+(*pindex))!='.') // so check for decimal point
return value; // and if not, return value

double factor = 1.0; // Factor for decimal places
while(isdigit(*(str+(++(*pindex))))) // Loop as long as we have digits
{
factor *= 0.1; // Decrease factor by factor of 10
value=value + (*(str+(*pindex))-48)*factor; // Add decimal place
}

return value; // On loop exit we are done
}

// Function to extract a substring between parentheses
// (requires string.h)
char * extract(char * str, int * pindex)
{
char buffer[MAX]; // Temporary space for substring
char * pstr = NULL; // Pointer to new string for return
int numL = 0; // Count of left parentheses found
int bufindex = *pindex; // Save starting value for index
do
{
buffer[(*pindex) - bufindex] = *(str + (*pindex));
switch(buffer[(*pindex) - bufindex])
{
case ')':
if(numL == 0)
{
buffer[(*pindex) - bufindex] = '\0'; // Replace ')' with '\0'
++(*pindex);
pstr = (char *) malloc((*pindex) - bufindex + 1);
if (!pstr)
{
printf("Memory allocation failed, program terminated.") ;
exit(1);
}
strcpy(pstr, buffer); // Copy substring to new memory
return pstr; // Return substring in new memory
}
else
numL--; // Reduce count of '(' to be matched
break;
case '(':
numL++; // Increase count of '(' to be // matched
break;
}
} while(*(str + (*pindex)++) != '\0'); // Loop - don't overrun end of string
printf("Ran off the end of the expression, must be bad input.\n");
exit(1);
}

...全文
317 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
赵4老师 2015-06-18
  • 打赏
  • 举报
回复
楼主如果还想在这方面探究下去的话: http://www.codeproject.com/Articles/286121/Compiler-Patterns 或 参考Tiny C Compiler源代码。
赵4老师 2015-06-18
  • 打赏
  • 举报
回复
前两天CSDN C/C++论坛离了zhao4zhong1这根胡萝卜还真开不了席了!
moritz_dev 2015-06-17
  • 打赏
  • 举报
回复
這個計算器 的計算,是不是只能計算 類似於a*b+c*d这样格式的表逹式? 對於三角函數,楼上已經說了。有對應的庫,google一下就有大把答案。
ID870177103 2015-06-17
  • 打赏
  • 举报
回复
原理的话 平方可以用二分法 三角函数貌似只能用级数
xiaodeerdeer 2015-06-17
  • 打赏
  • 举报
回复
再math中有好多库函数,可以利用
赵4老师 2015-06-17
  • 打赏
  • 举报
回复
仅供参考:
/*---------------------------------------
函数型计算器(VC++6.0,Win32 Console)程序由 yu_hua 于2007-07-27设计完成
功能:
目前提供了10多个常用数学函数:
    ⑴正弦sin
    ⑵余弦cos
    ⑶正切tan
    ⑷开平方sqrt
    ⑸反正弦arcsin
    ⑹反余弦arccos
    ⑺反正切arctan
    ⑻常用对数lg
    ⑼自然对数ln
    ⑽e指数exp
    ⑾乘幂函数∧
用法:
如果要求2的32次幂,可以打入2^32<回车>
如果要求30度角的正切可键入tan(Pi/6)<回车>
注意不能打入:tan(30)<Enter>
如果要求1.23弧度的正弦,有几种方法都有效:
sin(1.23)<Enter>
sin 1.23 <Enter>
sin1.23  <Enter>
如果验证正余弦的平方和公式,可打入sin(1.23)^2+cos(1.23)^2 <Enter>或sin1.23^2+cos1.23^2 <Enter>
此外两函数表达式连在一起,自动理解为相乘如:sin1.23cos0.77+cos1.23sin0.77就等价于sin(1.23)*cos(0.77)+cos(1.23)*sin(0.77)
当然你还可以依据三角变换,再用sin(1.23+0.77)也即sin2验证一下。
本计算器充分考虑了运算符的优先级因此诸如:2+3*4^2 实际上相当于:2+(3*(4*4))
另外函数名前面如果是数字,那么自动认为二者相乘.
同理,如果某数的右侧是左括号,则自动认为该数与括弧项之间隐含一乘号。
如:3sin1.2^2+5cos2.1^2 相当于3*sin2(1.2)+5*cos2(2.1)
又如:4(3-2(sqrt5-1)+ln2)+lg5 相当于4*(3-2*(√5 -1)+loge(2))+log10(5)
此外,本计算器提供了圆周率 Pi键入字母时不区分大小写,以方便使用。
----------------------------------------*/
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <cmath>
#include <stdio.h>
#include <string.h>
#include <windows.h>
using namespace std;
const char Tab=0x9;
const int  DIGIT=1;
const int MAXLEN=16384;
char s[MAXLEN],*endss;
int pcs=15;
double fun(double x,char op[],int *iop) {
    while (op[*iop-1]<32) //本行使得函数嵌套调用时不必加括号,如 arc sin(sin(1.234)) 只需键入arc sin sin 1.234<Enter>
        switch (op[*iop-1]) {
        case  7: x=sin(x);  (*iop)--;break;
        case  8: x=cos(x);  (*iop)--;break;
        case  9: x=tan(x);  (*iop)--;break;
        case 10: x=sqrt(x); (*iop)--;break;
        case 11: x=asin(x); (*iop)--;break;
        case 12: x=acos(x); (*iop)--;break;
        case 13: x=atan(x); (*iop)--;break;
        case 14: x=log10(x);(*iop)--;break;
        case 15: x=log(x);  (*iop)--;break;
        case 16: x=exp(x);  (*iop)--;break;
        }
    return x;
}
double calc(char *expr,char **addr) {
    static int deep; //递归深度
    static char *fname[]={ "sin","cos","tan","sqrt","arcsin","arccos","arctan","lg","ln","exp",NULL};
    double ST[10]={0.0}; //数字栈
    char op[10]={'+'}; //运算符栈
    char c,*rexp,*pp,*pf;
    int ist=1,iop=1,last,i;

    if (!deep) {
        pp=pf=expr;
        do {
            c = *pp++;
            if (c!=' '&& c!=Tab)
                *pf++ = c;
        } while (c!='\0');
    }
    pp=expr;
    if ((c=*pp)=='-'||c=='+') {
        op[0] = c;
        pp++;
    }
    last = !DIGIT;
    while ((c=*pp)!='\0') {
        if (c=='(') {//左圆括弧
            deep++;
            ST[ist++]=calc(++pp,addr);
            deep--;
            ST[ist-1]=fun(ST[ist-1],op,&iop);
            pp = *addr;
            last = DIGIT;
            if (*pp == '('||isalpha(*pp) && strnicmp(pp,"Pi",2)) {//目的是:当右圆括弧的右恻为左圆括弧或函数名字时,默认其为乘法
                op[iop++]='*';
                last = !DIGIT;
                c = op[--iop];
                goto operate ;
            }
        }
        else if (c==')') {//右圆括弧
            pp++;
            break;
        } else if (isalpha(c)) {
            if (!strnicmp(pp,"Pi",2)) {
                if (last==DIGIT) {
                    cout<< "π左侧遇)" <<endl;exit(1);
                }
                ST[ist++]=3.14159265358979323846264338328;
                ST[ist-1]=fun(ST[ist-1],op,&iop);
                pp += 2;
                last = DIGIT;
                if (!strnicmp(pp,"Pi",2)) {
                    cout<< "两个π相连" <<endl;exit(2);
                }
                if (*pp=='(') {
                    cout<< "π右侧遇(" <<endl;exit(3);
                }
            } else {
                for (i=0; (pf=fname[i])!=NULL; i++)
                    if (!strnicmp(pp,pf,strlen(pf))) break;
                if (pf!=NULL) {
                    op[iop++] = 07+i;
                    pp += strlen(pf);
                } else {
                    cout<< "陌生函数名" <<endl;exit(4);
                }
            }
        } else if (c=='+'||c=='-'||c=='*'||c=='/'||c=='%'||c=='^') {
            char cc;
            if (last != DIGIT) {
                cout<< "运算符粘连" <<endl;exit(5);
            }
            pp++;
            if (c=='+'||c=='-') {
                do {
                    cc = op[--iop];
                    --ist;
                    switch (cc) {
                    case '+':  ST[ist-1] += ST[ist];break;
                    case '-':  ST[ist-1] -= ST[ist];break;
                    case '*':  ST[ist-1] *= ST[ist];break;
                    case '/':  ST[ist-1] /= ST[ist];break;
                    case '%':  ST[ist-1] = fmod(ST[ist-1],ST[ist]);break;
                    case '^':  ST[ist-1] = pow(ST[ist-1],ST[ist]);break;
                    }
                } while (iop);
                op[iop++] = c;
            } else if (c=='*'||c=='/'||c=='%') {
operate:        cc = op[iop-1];
                if (cc=='+'||cc=='-') {
                    op[iop++] = c;
                } else {
                    --ist;
                    op[iop-1] = c;
                    switch (cc) {
                    case '*':  ST[ist-1] *= ST[ist];break;
                    case '/':  ST[ist-1] /= ST[ist];break;
                    case '%':  ST[ist-1] = fmod(ST[ist-1],ST[ist]);break;
                    case '^':  ST[ist-1] = pow(ST[ist-1],ST[ist]);break;
                    }
                }
            } else {
                cc = op[iop-1];
                if (cc=='^') {
                    cout<< "乘幂符连用" <<endl;exit(6);
                }
                op[iop++] = c;
            }
            last = !DIGIT;
        } else {
            if (last == DIGIT) {
                cout<< "两数字粘连" <<endl;exit(7);
            }
            ST[ist++]=strtod(pp,&rexp);
            ST[ist-1]=fun(ST[ist-1],op,&iop);
            if (pp == rexp) {
                cout<< "非法字符" <<endl;exit(8);
            }
            pp = rexp;
            last = DIGIT;
            if (*pp == '('||isalpha(*pp)) {
                op[iop++]='*';
                last = !DIGIT;
                c = op[--iop];
                goto operate ;
            }
        }
    }
    *addr=pp;
    if (iop>=ist) {
        cout<< "表达式有误" <<endl;exit(9);
    }
    while (iop) {
        --ist;
        switch (op[--iop]) {
        case '+':  ST[ist-1] += ST[ist];break;
        case '-':  ST[ist-1] -= ST[ist];break;
        case '*':  ST[ist-1] *= ST[ist];break;
        case '/':  ST[ist-1] /= ST[ist];break;
        case '%':  ST[ist-1] = fmod(ST[ist-1],ST[ist]);break;
        case '^':  ST[ist-1] = pow(ST[ist-1],ST[ist]);break;
        }
    }
    return ST[0];
}
int main(int argc,char **argv) {
    int a;

    if (argc<2) {
        if (GetConsoleOutputCP()!=936) system("chcp 936>NUL");//中文代码页
        cout << "计算函数表达式的值。"<<endl<<"支持(),+,-,*,/,%,^,Pi,sin,cos,tan,sqrt,arcsin,arccos,arctan,lg,ln,exp"<<endl;
        while (1) {
            cout << "请输入表达式:";
            gets(s);
            if (s[0]==0) break;//
            cout << s <<"=";
            cout << setprecision(15) << calc(s,&endss) << endl;
        }
    } else if (argc==2 && 0==strcmp(argv[1],"/?")) {
        if (GetConsoleOutputCP()!=936) system("chcp 936>NUL");//中文代码页
        cout << "计算由≥1个命令行参数给出的函数表达式的值。最后一个参数是.0~.15表示将计算结果保留小数0~15位"<<endl<<"支持(),+,-,*,/,%,^^,Pi,sin,cos,tan,sqrt,arcsin,arccos,arctan,lg,ln,exp"<<endl;
    } else {
        strncpy(s,argv[1],MAXLEN-1);s[MAXLEN-1]=0;
        if (argc>2) {
            for (a=2;a<argc-1;a++) strncat(s,argv[a],MAXLEN-1);//将空格间隔的各参数连接到s
            if (1==sscanf(argv[a],".%d",&pcs) && 0<=pcs && pcs<=15) {//最后一个参数是.0~.15表示将计算结果保留小数0~15位
                printf("%.*lf\n",pcs,calc(s,&endss));
            } else {
                strncat(s,argv[a],MAXLEN-1);
                printf("%.15lg\n",calc(s,&endss));
            }
        } else {
            printf("%.15lg\n",calc(s,&endss));
        }
    }
    return 0;
}
苏叔叔 2015-06-16
  • 打赏
  • 举报
回复
平方return x*x; 三角函数:直接库函数,#include <math.c> sin()
目 录 一、课设任务及要 1 二、需分析 2 三、设计思路 3 四、详细设计 5 五、运行调试与分析讨论 9 六、设计体会与小结 14 七、参考文献 15 附录 16 中文摘要 Java是由Sun Microsystems公司于1995年5月推出的Java程序设计语言和Java平台的总称。用Java实现 的HotJava浏览器,显示了Java的魅力:跨平台、动感的Web、Internet计算。从此,Ja va被广泛接受并推动了Web的迅速发展,常用的浏览器现在均支持Java applet。另一方面,Java技术也不断更新。Java平台由Java虚拟机和Java 应用编程接口构成。Java 应用编程接口为Java应用提供了一个独立于操作系统的标准接口,可分为基本部分和扩 展部分。在硬件或操作系统平台上安装一个Java平台之后,Java应用程序就可运行。现 在Java平台已经嵌入了几乎所有的操作系统。这样Java程序可以只编译一次,就可以在 各种系统中运行。 Java分为三个体系J2SE,J2EE,J2ME。 说起计算器,值得我们骄傲的是,最早的计算工具的诞生地是中国。 在17世纪初,西方国家的计算工具才有了较大的发展,英国数学家纳皮尔发明的"纳 皮尔算筹",英国牧师奥却德发明了圆柱型对数计算尺,这种计算尺不仅能做加减乘除、 乘方、开方运算,甚至可以计算三角函数,指数函数和对数函数,这些计算工具不仅带 动了计算器的发展,也为现代计算器发展奠定了良好的基础,进而成为了现代社会应用 广泛的计算工具。 关键词:java Java平台 计算器 课设任务及要 1.课设任务 这次课程设计选择的题目为设计一个图形界面(GUI)的计算器应用程序,完成简单 的算术运算。 这次课程设计的基本要为设计的计算器应用程序可以完成加法、减法、乘法、除 法和取余运算,且有小数点、正负号、倒数、退格和清零功能。拓展功能根据自己的 能力添加。 这次课程设计的我选择添加的拓展功能为开平方根,平方,立方,判断素数,lo g的功能。 本程序主要练习使用布局管理器设计一个计算器的界面,并练习使用事件监听器处 理数据的输入,并完成相关的计算。数据和运算符号的存储采用动态链表这种数据结构 实现。 这次课程设计选择的Java运行环境为: Windows XP sp3 +Eclipse+JDK 1.6 二、需分析 1.系统功能分析 计算器是现在一个普遍应用的工具,能够解决许多人所无法计算的数据,节省大量 宝贵的时间。 2.系统功能分析 为了实现计算器系统的功能.主要有二个功能模块:输入、输出。 3.系统设计原则 基于计算器系统要具有适用性广、操作简便等特点.本系统预计要达到以下几个目标 : (1)、满足以上的功能; (2)、能够运行在常见的计算机及其配置上; 三、设计思路 1.关于布局问题 本次课程设计程序继承来自框架类(Frame),总体布局上选用布局管理器BorderLayout: (1)将单行文本框加入到"North"区域 (2)将面板panel加入到"Center"区域,同时panel包含了各种数字按钮和符号按钮。 面板panel采用Girdlayout布局,选用5行*5列,将各种按钮添加到面板panel,并增加按 钮监听事件。 布局完成后的效果图如下: 2.关于数据存储问题 计算器完成的是一个数学表达式,本次课程设计我选用的是使用链表(Linkedlist类 )来存储数字和运算符号。程序运行后,输入的所有数字及运算符号都全部存储在链表中 ,待最后运算时,再一一出来进行计算。 3.关于事件监听的处理问题 计算器的各种按钮都需要一个对象来进行监视,以便对发生的事件做出处理。计算器 的各种按钮通过调用相应的方法将某个对象作为自己的监视器。 例如计算器中的数字按钮,其方法为: AddActionListener(监视器); 对于获取了监视器的数字按钮,通过相应的操作就会导致事件的发生,并通知监视器 ,监视器就会做出相应的处理。 四、详细设计 1.计算器系统主要功能模块 (1)、系统主要模块实现的功能 系统输入模块实现数字以及计算符号输入的功能,输出模块的结果在文本框中实现显 示。 (2)、系统输入窗体实现的效果 系统输入窗体设计效果如图所示: 上图为按数字键1234567890后,在文本框中的显示 (3)、系统主要模块功能描述 功能描述: 菜单项"计算器"主要服务于使用者.它包含了"输入"、"输出"、 两个功能。 输入功能:当使用者将数字输入后,会出现数字的显示;当使用者将计算符号输入时 候会有计算符号的录入。 输出功能:点击"输出"选项后.可实现计算的结果。 2.系统的实现 (1) 系统源文件类之间的关系 计算器系统共有3个java源文件:Calcul

69,368

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧