標(biāo)題: c語(yǔ)言計(jì)算器程序(簡(jiǎn)單) [打印本頁(yè)]

作者: liuyuxi    時(shí)間: 2015-1-11 00:18
標(biāo)題: c語(yǔ)言計(jì)算器程序(簡(jiǎn)單)
/*************************************************
名稱(chēng):計(jì)算器程序日期:2015年月1月11號(hào)
編寫(xiě):掃帚菜(大鶴)
內(nèi)容:通過(guò)此程序,實(shí)現(xiàn)簡(jiǎn)單的四則運(yùn)算
**************************************************/
#include "stdio.h"
#include "stdlib.h"
float get_num(char **);

int main()
{
    char a[80];
    int sign = 1;/*正負(fù)號(hào)的標(biāo)志*/
    float result = 0;
    char *p;
    clrscr();
    gets(a); /*由此輸入字符*/
    p=a;
    if(*p=='-') /*如果第一個(gè)字符為'-'號(hào)則標(biāo)志為負(fù)*/
    {
        sign=-1;
        p++;   /*指向下一個(gè)字符*/
    }
    while(*p!=0)
    {
        float  m;
        m=sign*get_num(&p);/*m被賦值為字符串的第一個(gè)數(shù)*/
        while(*p=='*'||*p=='/')/*如果字符為'*'或'/'則一直進(jìn)行*/
        {
            if(*p=='*')
            {
                p++;
                m*=get_num(&p);
            }
            else
            {
                int div;
                p++;
                div=get_num(&p);
            if(div==0)
            {
                printf("個(gè)驢!除數(shù)怎么為0?瘋了吧~~~\n");
                exit(1);
            }
            else
            m/=div;
        }
    }
    if(*p!='+'&&*p!='-'&&*p!=0)
    {
         printf("哈哈,非法字符=非法同居: %c\n",*p);
         exit(0);
    }

    result+=m;
    if(*p=='+')
    {
        sign=1;
        p++;
     }
    else if(*p=='-')
    {
        sign=-1;
        p++;
    }
    else
        break;
   }
printf("The result is %f\n", result);
getch();
return 0;
}
/*****************************************************
以下函數(shù)為計(jì)算函數(shù),涉及較多指針和二級(jí)指針的知識(shí),為C程
序比較難的部分,不做過(guò)多注釋?zhuān)驗(yàn)橹粫?huì)越注越亂看不懂可
以問(wèn)我,在下雖然是個(gè)菜鳥(niǎo),但在這個(gè)程序上還得算是個(gè)老鳥(niǎo)
******************************************************/
float get_num(char **p)
{
    float n =0, m = 10;
    if(**p!='.'&&(**p<'0'||**p>'9'))
   {
        printf("不長(zhǎng)腦子。亂輸什么?運(yùn)算符后面不是數(shù)行吧\n");
        exit(1);
   }
    while(**p>='0'&&**p<='9')
    {
        n=n*10+**p-48;
        (*p)++;
    }
   if(**p=='.')
   {
        (*p)++;
        while(**p>='0' &&**p<='9')
        {
             n+=(**p-48)/m;
             (*p)++;
             m*=10;
        }
   }
return n;
}







歡迎光臨 (http://www.torrancerestoration.com/bbs/) Powered by Discuz! X3.1