Chinaunix首页 | 论坛 | 博客

分类: C/C++

2014-12-15 11:12:33


点击(此处)折叠或打开

  1. #include<stdio.h>

  2. double calculator (double a,double b,char operation)//定义计算器需要的变量,a b 以及操作符“+” “-” “*” “/
  3. {
  4.     if ( operation=='+')//如果操作符为“+”,那么进行如下计算
  5.         return a+b; //返回到a+b,就是计算出a+b
  6.     
  7.     else if(operation=='-')
  8.         return a-b;

  9.     else if(operation=='*')
  10.         return a*b;

  11.     else if(operation=='/')
  12.     {
  13.         if(b==0) //除法中,除数不能为0,在这里要特定一下
  14.         {
  15.             printf("除数不能为0\n");
  16.             return 0;
  17.         }
  18.         else
  19.         {
  20.             return a/b;
  21.         }
  22.     }
  23.     else
  24.     {
  25.         printf("bad operation...\n");
  26.         return 0;
  27.     }
  28. }

  29. int main()//调用函数
  30. {
  31.     double a,b;
  32.     char operation;
  33.     scanf("%lf%c%lf",&a,&operation,&b);//在键盘上任意获取两个变量与一个操作符
  34.     printf("%.2lf\n",calculator(a,b, operation));//结果保留了两位小数
  35.     return 0;
  36. }

阅读(2622) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~