在objective-c代码

时间:2016-07-05 08:12:07

标签: objective-c xcode

我有以下代码从用户那里获取并确定operator+, -, *, /之一,如果不是unknown operator。现在它运行良好,除非我输入ˆ字符然后程序挂起没有看到输出。我觉得代码看不到ˆ是有效字符。如何让我的代码看到ˆ。记住我是objective-c的新手,我的例子来自我正在关注的教程。

//
//  main.m
//  ex-6.8
//
//  Created by george on 30/06/2016.
//  Copyright © 2016 george. All rights reserved.
//  Program to evaluate simple expressions of the
//  form number operator number

#import <Foundation/Foundation.h>


@interface Calculator : NSObject
{
    double accumulator;
    //char operator;
}

// accumulator methods
- (void) setAccumulator: (double) value;
- (void) clear;
- (double) accumulator;

// arithmetic methods

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

@end


@implementation Calculator
- (void) setAccumulator:(double)value
{
    accumulator = value;
}

- (void) clear
{
    accumulator = 0;
}

- (double) accumulator
{
    return accumulator;
}

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

- (void) subtract:(double)value
{
    accumulator -= value;
}

- (void) multiply:(double)value
{
    accumulator *= value;
}

- (void) divide:(double)value
{
    if( value != 0.0)
        accumulator /= value;
        else{
            NSLog(@"Division by zero.");
            accumulator = NAN;
        }
}

@end

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // insert code here...
        double value1, value2;
        char operator;
        Calculator *deskCalc = [[Calculator alloc] init];

        NSLog(@"Type in your expression.");
        scanf("%lf %c %lf", &value1, &operator, &value2);


        [deskCalc setAccumulator:value1];

        switch (operator) {
            case '+':
                [deskCalc add: value2];
                NSLog(@"%.2f", [deskCalc accumulator]);
                 break;
            case '-':
                [deskCalc subtract: value2];
                NSLog(@"%.2f", [deskCalc accumulator]);
                break;
            case '*':
                [deskCalc multiply: value2];
                NSLog(@"%.2f", [deskCalc accumulator]);
                break;
            case '/':
                [deskCalc divide: value2];
                NSLog(@"%.2f", [deskCalc accumulator]);
                break;
            default:
                NSLog(@"Unknown operator.");
                break;
        }


    }
    return 0;
}

0 个答案:

没有答案