例3-11 四则运算

例3-11 四则运算

在例3-9、例3-5的基础上增加对除数是否为零的判断
程序核心——if语句

程序

#include<stdio.h>
int main()
{
    double value1,value2;
    char op;
    
    printf("Type in an expression:");
    scanf("%lf%c%lf",&value1,&op,&value2);
    
    if(op=='+')
        printf("=%.2f\n",value1+value2);
    else if (op=='-')
        printf("=%.2f\n",value1-value2);
    else if (op=='*')
        printf("=%.2f\n",value1*value2);
    else if (op=='/')
        if(value2!=0)
            printf("=%.2f\n",value1/value2);
        else
            printf("Divisor can not be 0!\n"); 
    else
        printf("Unknown operator\n");
    return 0;
 }  

结果

Type in an expression:9/0
Divisor can not be 0!

--------------------------------
Process exited after 7.105 seconds with return value 0
请按任意键继续. . .

分析

重点:

猜你喜欢

转载自www.cnblogs.com/5236288kai/p/10582604.html
今日推荐