首页 > 代码库 > 7,指针用法,计算器代码
7,指针用法,计算器代码
#define _STDC_WANT_LIB_EXT1_ 1 #include <stdio.h> #include <string.h> #include <ctype.h> #include <stdlib.h> #include <stdbool.h> #include <math.h> #define BUF_LEN 256 int main(void) { char buf[BUF_LEN]; //char number_string[30]; char op = 0; //操作符 size_t index = 0; size_t to =0; size_t buf_length = 0; //unsigned int number_length = 0; double result = 0.0; double number =0.0; char *endptr = NULL; printf("To use this calculator, enter any expression with" " or without spaces."); printf("\nAn expression may include the operators"); printf(" +, -, *, /, %%, or ^(raise to a power)."); printf("\nUse = at the beginning of a line to operate on "); printf("\nthe result of the previous calculation."); printf("\nEnter quit to stop the calculator.\n\n"); //1.读入用户输入的字符串,是quit,就退出 char *ptr =NULL; while(true) { ptr = fgets(buf,BUF_LEN,stdin); if(ptr == false)//测试 { printf("Error reading input.\n"); return 1; } if(strcmp(buf,"quit\n")==0) break; buf_length = strnlen_s(buf,BUF_LEN); buf[--buf_length] = ‘\0‘; //2.从输入字符串中删除空格 for(to = 0,index = 0;index<=buf_length;++index) { if(*(buf+index)!=‘ ‘) *(buf+ to++) = *(buf+index); } buf_length = strnlen_s(buf,BUF_LEN); //3.在输入字符串中的开头检查 = 运算符, //如果有一个=运算符就把上一个输入字符串的结果作为下一个算数操作的左操作数。查找第一个操作数 index = 0; if(buf[index]==‘=‘) index++; else { //4.给下一个算数操作的左操作数提取相应的输入字符,把该字符串转换为double类型 result = strtod(buf+index,&endptr);//转换并存储数字 printf("%s\n",endptr); index = endptr-buf; //获取下一个字符的索引 } //5.提取算数运算符,记录它。 while(index < buf_length) { op = *(buf+index++); //6.给右操作数提取相应的输入字符,把该子字符串转换为double类型 number = strtod(buf+index,&endptr); index = endptr - buf; //7.执行运算,把结果存储为下一个左操作数 switch(op) { case ‘+‘: result += number; break; case ‘-‘: result -= number; break; case ‘*‘: result *= number; break; case ‘/‘: if(number == 0) printf("\n\n\aDivision by zero error!\n"); else result /= number; break; case ‘%‘: if((long long)number == 0LL) printf("\n\n\aDivision by zero error!\n"); else result = (double)((long long)result % (long long)number); break; case ‘^‘: result = pow(result,number); break; default: printf("\n\n\aIllegal operation!\n"); break; } } //8.如果不是字符串的末尾,就返回第6步,如果在字符串的末尾,就返回第一步 printf("= %f\n",result); } return 0; }
7,指针用法,计算器代码
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。