Object-C,四则运算计算器


下面是是一个比较复杂的类。

定义一个四则运算计算器Caculator的接口和实现。

在main函数中,让用户输入四则运算表达式,比如a+b,a-b。

最后,在控制台输出结果。


用到的语法:接口、类的定义,实例方法,switch-case语句。


/

/
//  main.m
//  switch-case
//
//  Created by fansunion on 15/11/15.
//  Copyright (c) 2015年 demo. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface Caculator : NSObject
-(void)setValue:(double)value;
-(double)getResult;

-(void)add:(double)value;
-(void)sub:(double)value;
-(void)multiply:(double)value;
-(void)divide:(double)value;

@end

@implementation Caculator

{
    double value;
}

-(void)setValue:(double)v{
    value=v;
}

-(void)add:(double)v{
    value+=v;
}

-(void)sub:(double)v{
    value-=v;
}
-(void)multiply:(double)v{
    value*=v;
}
-(void)divide:(double)v{
    value/= v;
}
-(double)getResult{
return value;
}


@end
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        double value = 0;
        double v=0;
        char operator;
        Caculator *caculator =[[Caculator alloc]init];
        NSLog(@"请输入表达式!");
        scanf("%lf %c %lf",&value,&operator,&v);
        [caculator setValue:value];
        switch(operator){
                case '+':
                [caculator add:v];
                break;
                case '-':
                [caculator sub:v];
                break;
                case '*':
                [caculator multiply:v];
                break;
                case '/':
                [caculator divide:v];
                break;
                default:
                NSLog(@"未知的操作符");
                break;
        }
        NSLog(@"%.2f",[caculator getResult]);
    }
    return 0;
}


加法,2015+2014=4029

2015-11-15 17:23:13.722 switch-case[1684:89106] 请输入表达式!

2015+2014

2015-11-15 17:23:21.586 switch-case[1684:89106] 4029.00

Program ended with exit code: 0


减法,2015-2020=-5

2015-11-15 17:23:44.579 switch-case[1688:89497] 请输入表达式!

2015-2020

2015-11-15 17:23:55.500 switch-case[1688:89497] -5.00

Program ended with exit code: 0


乘法,2015*10=20150

2015-11-15 17:24:35.764 switch-case[1692:89985] 请输入表达式!

2015*10

2015-11-15 17:24:45.414 switch-case[1692:89985] 20150.00

Program ended with exit code: 0


除法,2015/10=201.5

2015-11-15 17:24:58.379 switch-case[1696:90264] 请输入表达式!

2015/10

2015-11-15 17:25:10.669 switch-case[1696:90264] 201.50

Program ended with exit code: 0


学习这个例子,感觉瞬间回到了2008年上半学年,大一上学期~

发布了1312 篇原创文章 · 获赞 2514 · 访问量 337万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 猿与汪的秘密 设计师: 上身试试

分享到微信朋友圈

×

扫一扫,手机浏览