iOS 简易计算器 纯代码

这篇博客介绍了如何使用纯代码在iOS平台上实现一个简单的计算器应用。通过创建`CaculatorBrain`类来封装计算逻辑,包括加减乘除以及清零等功能,并在`MxlJisuanqiViewController`中实现用户界面交互。计算器界面包含数字、运算符和清除键,并能处理连续运算和等于号的点击事件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >




把  计算器里的方法 封装一个类

#import <Foundation/Foundation.h>


@interface CaculatorBrain : NSObject



- (void)pushOperation:(NSString *)operation;

- (double)result:(BOOL)secondEq;

- (void)zero;

- (void)pushNumberInStack:(double)aDouble  andBool:(BOOL)aBool;


@end


#import "CaculatorBrain.h"

@class MxlJisuanqiViewController;

@interface CaculatorBrain()


@property (strong,nonatomic)NSMutableArray *operandStack;


@property (assign,nonatomic)unichar symbol;

@property (weak,nonatomic)MxlJisuanqiViewController *controller;

@property (assign,nonatomic)double secondNumber;


@end




@implementation CaculatorBrain


- (NSMutableArray *)operandStack

{

    if (!_operandStack) {

        _operandStack = [NSMutableArray arrayWithCapacity:3];

    }

    return _operandStack;

}



- (double)outANumber

{

    

    double number = [[self.operandStack lastObject]doubleValue];

    if ([self.operandStack lastObject]){

        [self.operandStack removeLastObject];

      }

 

        return number;


   

}


- (double)result:(BOOL)secondEq

{

     NSString *opera = [NSString stringWithFormat:@"%c",self.symbol];

    if (!secondEq){

        if ([self.operandStack count] >1 ){

            double number2 = [self outANumber];

            double number1 = [self outANumber];

           

            double result = 0;

            if ([opera isEqualToString:@"+"]) result = number1 + number2;

            else if ([@"-" isEqualToString:opera]) result = number1 - number2;

            else if ([opera isEqualToString:@"×"]) result = number1 * number2;

            

            else if ([opera isEqualToString:@"÷"])

            {

                if (number2 == 0) {

                    

                    

                }else

                {

                result = number1 / number2;

                }

            }else if ([opera isEqualToString:@""])

            {

                return result = number1;

            }

   

            return result;

        }

        else

        {

            [self zero];

            return  0;

        }

    }else {

     

        double number = [self outANumber];

      

        

        double result  = 0;

        if ([opera isEqualToString:@"+"]) result = number + self.secondNumber;

        else if ([@"-" isEqualToString:opera]) result = number - self.secondNumber;

        else if ([opera isEqualToString:@"×"]) result = number * self.secondNumber;

        else if ([opera isEqualToString:@"÷"])

        {

            if (self.secondNumber == 0) {

                

            }else

            {

            result = number / self.secondNumber;

            }

        }


        return  result;

    }

    

}

- (void)zero {

    [self.operandStack removeAllObjects];

   

  

  

}

- (void)pushNumberInStack:(double)aDouble  andBool:(BOOL)aBool {

  

    double number = aDouble;

    NSNumber *operand = [NSNumber numberWithDouble:number];

    [self.operandStack addObject:operand];

    if(!aBool) {

        self.secondNumber = [[self.operandStack lastObject]doubleValue];}

   

    

}

- (void)pushOperation:(NSString *)operati

{

    self.symbol = [operati characterAtIndex:0];

    

   

}

@end



在计算器界面里 


在.h  文件里

#import <UIKit/UIKit.h>


@interface MxlJisuanqiViewController : UIViewController


@property (nonatomic,retain)NSString *disStr;

@end


在.m  文件里

#import "MxlJisuanqiViewController.h"

#import "CaculatorBrain.h"


@interface MxlJisuanqiViewController ()

@property (nonatomic, retain)  UILabel *display;

@property BOOL isUseInEnteringANumber;

@property (nonatomic)CaculatorBrain *brain;

@property BOOL isContinue;

@property BOOL secondEqual;

@property BOOL firstEqual;

@property (nonatomic,retain)NSUserDefaults*userDefaults;

@end


@implementation MxlJisuanqiViewController

@synthesize userDefaults;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

{

    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

    if (self) {

        userDefaults = [NSUserDefaults standardUserDefaults];

    }

    return self;

}


- (CaculatorBrain *)brain

{

    if (!_brain) {

        _brain = [CaculatorBrain new];

    }

    return _brain;

}


- (void)viewDidLoad

{

    [super viewDidLoad];

    

    

    NSArray *familyNames =[[NSArray alloc]initWithArray:[UIFont familyNames]];

    NSArray *fontNames;

    NSInteger indFamily, indFont;

    NSLog(@"[familyNames count]===%d",[familyNames count]);

    for(indFamily=0;indFamily<[familyNames count];++indFamily)

        

    {

        NSLog(@"Family name: %@", [familyNames objectAtIndex:indFamily]);

        fontNames =[[NSArray alloc]initWithArray:[UIFont fontNamesForFamilyName:[familyNames objectAtIndex:indFamily]]];

        

        for(indFont=0; indFont<[fontNames count]; ++indFont)

            

        {

            NSLog(@"Font name: %@",[fontNames objectAtIndex:indFont]);

            

        }

        

            }


    //    titleViewlabel

    UILabel *titleLab = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 30)];

    titleLab.text = @"计算器";

    titleLab.font = [UIFont fontWithName:@"Helvetica-Bold" size:18];

    titleLab.textColor = [UIColor whiteColor];

    titleLab.textAlignment = NSTextAlignmentCenter;

    self.navigationItem.titleView = titleLab;

    

    

    

    self.display = [[UILabel alloc]initWithFrame:CGRectMake(0, 64, 320, 92)];

    self.display.font = [UIFont systemFontOfSize:40.0f];

    self.display.textAlignment = NSTextAlignmentRight;

    self.display.text = self.disStr;

//    self.display.text = [userDefaults objectForKey:@"tf2"];


    NSLog(@"%@",self.display.text);

    self.display.backgroundColor = [UIColor colorWithRed:236/255. green:236/255. blue:236/255. alpha:1];

    [self.view addSubview:self.display];

    

    NSArray *shuziArr = @[@"AC",@"-",@"+",@"7",@"8",@"9",@"4",@"5",@"6",@"1",@"2",@"3",@"0",@".",@"00"];

    

    for(int i=0; i<5; i++) {

        for(int j=0; j<3; j++) {

            UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];

            if (isPhone5) {

                btn.frame = CGRectMake(80*j, 156+83*i, 80, 83);


            }else

            {

                btn.frame = CGRectMake(80*j, 156+65*i, 80, 65);


            }

           

            [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

            if (i ==0 ) {

                if (j ==0) {

                     [btn addTarget:self action:@selector(zeroPressed:) forControlEvents:UIControlEventTouchUpInside];

                }else

                {

                [btn addTarget:self action:@selector(operationPressed:) forControlEvents:UIControlEventTouchUpInside];

                }

                

                btn.backgroundColor = [UIColor colorWithRed:120/255. green:193/255. blue:42/255. alpha:0.76];

//                btn.backgroundColor = [UIColor  lightGrayColor];


            }else

            {

                btn.backgroundColor = [UIColor colorWithRed:236/255. green:236/255. blue:236/255. alpha:1];


                [btn addTarget:self action:@selector(digitPressed:) forControlEvents:UIControlEventTouchUpInside];

            }

            

            btn.titleLabel.font= [UIFont fontWithName:@"HelveticaNeue-Thin" size:25.0];

//            btn.titleLabel.font = [UIFont systemFontOfSize:25.0f];

            [btn setTitle:[shuziArr objectAtIndex:3*i+j] forState:UIControlStateNormal];

            


//            [btn setTitleShadowColor:[UIColor redColor] forState:UIControlStateSelected];


            btn.tag = 3*i+j;

            [self.view addSubview:btn];

        }

    }

   

   

    NSArray *yunsuanArr  =@[@"÷",@"×",@"=",@"OK"];

    for (int i = 0; i<4; i++) {

        UIButton *buttons = [UIButton buttonWithType:UIButtonTypeRoundedRect];

        if (i ==3) {

            if (isPhone5) {

                buttons.frame = CGRectMake(240, 156+83*i, 80, 166);


            }else

            {

                buttons.frame = CGRectMake(240, 156+65*i, 80, 130);


            }


            [buttons addTarget:self action:@selector(okBtn:) forControlEvents:UIControlEventTouchUpInside];

            buttons.backgroundColor = [UIColor colorWithRed:120/255. green:193/255. blue:42/255. alpha:0.76];

//            buttons.backgroundColor = [UIColor  lightGrayColor];



        }else if(i ==2)

        {

            if (isPhone5) {

                buttons.frame = CGRectMake(240, 156+83*i, 80, 83);

                

            }else

            {

                buttons.frame = CGRectMake(240, 156+65*i, 80, 65);

                

            }

            [buttons addTarget:self action:@selector(equalR) forControlEvents:UIControlEventTouchUpInside];

              buttons.backgroundColor =[UIColor colorWithRed:120/255. green:193/255. blue:42/255. alpha:0.76];

//            buttons.backgroundColor = [UIColor  lightGrayColor];


//            [buttons setTitleColor:[UIColor  blackColor] forState:UIControlStateNormal];

//            buttons.titleLabel.font = [UIFont fontWithName:@"Copperplate" size:25];

//            [buttons setTitle:[yunsuanArr objectAtIndex:i] forState:UIControlStateNormal];

        }

        else

        {

            if (isPhone5) {

                buttons.frame = CGRectMake(240, 156+83*i, 80, 83);


            }else

            {

                buttons.frame = CGRectMake(240, 156+65*i, 80, 65);


            }

            buttons.backgroundColor = [UIColor colorWithRed:120/255. green:193/255. blue:42/255. alpha:0.76];

//            buttons.backgroundColor = [UIColor  lightGrayColor];



            [buttons addTarget:self action:@selector(operationPressed:) forControlEvents:UIControlEventTouchUpInside];


        }

        

        [buttons setTitleColor:[UIColor  blackColor] forState:UIControlStateNormal];

        buttons.titleLabel.font = [UIFont fontWithName:@"HelveticaNeue-Thin" size:25.0];

//        buttons.titleLabel.font = [UIFont systemFontOfSize:25.0f];

        [buttons setTitle:[yunsuanArr objectAtIndex:i] forState:UIControlStateNormal];


        

        [self.view addSubview:buttons];


        

    }

    

    

    for (int i = 0; i<5; i++) {

        UIImageView *imageview = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"divider1.png"]];

        if (i ==4) {

            if (isPhone5) {

                imageview.frame = CGRectMake(0, 155.6+83*i, 240, 1.1);


            }else

            {

                imageview.frame = CGRectMake(0, 155.6+65*i, 240, 1.1);


            }


        }else

        {

            if (isPhone5) {

                imageview.frame = CGRectMake(0, 155.6+83*i, 320, 1.1);


            }else

            {

                imageview.frame = CGRectMake(0, 155.6+65*i, 320, 1.1);


            }

        }

        [self.view addSubview:imageview];


    }

    

    for (int i = 0; i<3; i++) {

        UIView *lineView = [[UIView alloc] init ];

        if (i ==1) {

            if (isPhone5) {

                lineView.frame =CGRectMake(80*i+80, 156.0f, 0.60f, 415.0f);


            }else

            {

                lineView.frame =CGRectMake(80*i+80, 156.0f, 0.60f, 330.0f);


            }

        }else

            if (isPhone5) {

                lineView.frame =CGRectMake(80*i+80, 156.0f, 0.60f, 415.0f);

                

            }else

            {

                lineView.frame =CGRectMake(80*i+80, 156.0f, 0.60f, 330.0f);

                

            }        [lineView setBackgroundColor:[UIColor lightGrayColor]];

        [self.view addSubview:lineView];

    }

    

    

    }


-(void)viewWillAppear:(BOOL)animated

{

    [super viewWillAppear:YES];

    self.navigationItem.hidesBackButton = YES;

    

}


-(void)viewWillDisappear:(BOOL)animated

{

    self.display.text = @"";

}

// 点击操作符号

-(void)operationPressed:(UIButton*)sender

{

    self.firstEqual = YES;

    _secondEqual = NO;

    if(_isContinue) [self equalR];

    [self.brain pushOperation:sender.currentTitle];

    

    [self numberInBrain];

    _isContinue = YES;

}


- (void)numberInBrain

{

    _isUseInEnteringANumber = NO;

    

    

    [self.brain pushNumberInStack:[self.display.text doubleValue] andBool:self.secondEqual];

}


// 清空

-(void)zeroPressed:(id)sender

{

    self.display.text = @"0";

    [self.brain zero];

    _isContinue = NO;

    _isUseInEnteringANumber = NO;

    

    [self.brain pushNumberInStack:0.0 andBool:NO];

    self.secondEqual = NO;

    self.firstEqual = NO;

    


}


//  点击数字按钮

-(void)digitPressed:(UIButton*)sender

{

    _secondEqual = NO;

    NSString *digit = sender.currentTitle;

    if (_isUseInEnteringANumber == YES)

    {

        self.display.text = [self.display.text stringByAppendingString:digit];

    }

    else {

        if ([digit isEqualToString:@"0"]) {

            self.display.text = @"0";

            _isUseInEnteringANumber = NO;

            

        }else if ([digit isEqualToString:@"."])

        {

            self.display.text = @"0.";

            _isUseInEnteringANumber = YES;

        }

        else

        {

        self.display.text = digit;

        _isUseInEnteringANumber = YES;

        }

    }

    NSLog(@"%@",digit);



}


// 点击等号

-(void)equalR

{

    if (self.firstEqual) {

        

        

        _isContinue = NO;

        [self numberInBrain];

        double resultNumber = [self.brain result:_secondEqual];

        NSLog(@"%e",resultNumber);

        NSMutableString *resultStr = [NSMutableString stringWithFormat:@"%lg",resultNumber];

        NSLog(@"%@",resultStr);

//           NSMutableString *resultStr = [NSMutableString stringWithFormat:@"%lf",resultNumber];

    

        

        if(resultNumber>1000000000){

            

            int count = 0;

            while (resultNumber >=10) {

                resultNumber/= 10;

                count++;

            }

            [resultStr deleteCharactersInRange:NSMakeRange(0, [resultStr length])];

            [resultStr appendFormat:@"%lg",resultNumber];

            [resultStr appendFormat:@" E%d",count];

            


            

        }

        self.display.text = resultStr;

        _secondEqual = YES;

    }else {

        NSLog(@"right!");

        double resultNumber = [self.display.text doubleValue];

        NSMutableString *resultStr = [NSMutableString stringWithFormat:@"%lg",resultNumber];

        if(resultNumber>1000000000){

            

            double count = 0.0;

            while (resultNumber >=10) {

                resultNumber /= 10.0;

                count += 1.0;

            }

            [resultStr deleteCharactersInRange:NSMakeRange(0, [resultStr length])];

            [resultStr appendFormat:@"%lg",resultNumber];

            [resultStr appendFormat:@"e%g",count];

            

        }

        self.display.text = resultStr;

//       [resultStr deleteCharactersInRange:NSMakeRange(0, [resultStr length])];

    }

    self.firstEqual = YES;

    

    


    

}


-(void)okBtn:(id)sender

{

    

    [userDefaults setObject:self.display.text forKey:@"value"];

    [self.navigationController popViewControllerAnimated:YES];

}


- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


@end


这个 计算器  没有 实现 优先级的 比较 。  有做出来的  求教 。。。 谢谢


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值