开发者

While Loop with a Nested Switch in Objective-C

I've just started learning Objective-C. I'm doing one of the standard calculator exercises. It's supposed to create an adding machine (e.g., input the operator and number, display the result each time). But I messed up something, and I think it has to do with my use of the "char" data type.

Here's the code, just the program section (interface and implementation are straightforward and worked in another version; still, if anyone wants to see them, just ask):

int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
double      value1 = 0.0;
char        operator = 'a';

Calculator *deskCalc = [[Calculator alloc] init];

NSLog(@"Initial value?");
scanf("%lf",&value1);

[deskCalc setAccumulator: value1];

while (operator != 'e') {
    {
    NSLog(@"Operation and value?");
    scanf("%c %lf", &开发者_JS百科operator, &value1);
    }
    switch (operator){
        case '+':
            [deskCalc add: value1];
            NSLog(@"%f", [deskCalc accumulator]);
            break;
        case '-':
            [deskCalc subtract: value1];
            NSLog(@"%f", [deskCalc accumulator]);
            break;
        case '*':
        case 'x':
            [deskCalc multiply: value1];
            NSLog(@"%f", [deskCalc accumulator]);
            break;
        case '/':
            if (value1 != 0) {
                [deskCalc divide: value1];
                NSLog(@"%f", [deskCalc accumulator]);
            }
            else {
                NSLog(@"Division by zero not allowed.");
                NSLog(@"%f", [deskCalc accumulator]);                   
            }
            break;
        case 's': 
            [deskCalc setAccumulator: value1];
            NSLog(@"%f", [deskCalc accumulator]);
            break;
        case 'e':
            NSLog(@"Done, sucker, final answer: %f.", value1);
        default:
            NSLog(@"Unknown operator.");
            NSLog(@"%f", [deskCalc accumulator]);
            break;
            

}
}

    [deskCalc release];
 
[pool drain];
return 0;

}   

And, in case it helps, here's what I get from the terminal when I run this:

From the terminal:

Initial value?

12 // My input

Operation and value?

x 4 // My input

Unknown operator.

Operation and value? // It doesn't stop to ask for input.

48.000000

Operation and value?

Help and thanks.

P.S. I know the program is pretty clunky. Have mercy, the last language I learned was Basic on my Coleco Adam, which had a tape drive--yeah, like a cassette tape, which was awesome.


scanf(" %c %lf", &operator, &value1);

Put a space between the open quotes and the %c, to trap any whitespace that is remaining on stdin.


operator is mostly \n. You will probably need to do a flushall().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜