开发者

Declared but unset variable evaluates as true?

开发者 https://www.devze.com 2023-04-06 14:37 出处:网络
I was doing a simple calculator with the following code. Right now it executes perfectly. When I tried to change things around, however, it doesn\'t work. I used BOOL program to check whether to conti

I was doing a simple calculator with the following code. Right now it executes perfectly. When I tried to change things around, however, it doesn't work. I used BOOL program to check whether to continue asking for input from the person or finish the program.

If I change the expression of while statement to just (program) and change YES/NO in the program statements, why does the code fail to do what is inside the while?

// A simple printing calculator
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]
    Calculator *deskCalc = [[Calculator alloc] init];
    double value1;
    char operator        
    BOOL program;

    [deskCalc setAccumulator: 0];

    while (!program) {
    NSLog (@"Please type in your expression");
    scanf (" %lf %c", &value1, &operator);
    program = NO;

        if (operator == '+') {
            [deskCalc add: value1];
        }
        else if (operator == '-') {
            [deskCalc subtract: value1];
        }
        else if (operator == '*' || operator == 'x') {
            [deskCalc multiply: value1];
        }
        else if (operator == '/') {
            if (value1 =开发者_运维百科= 0)
                NSLog (@"Division by zero!");
            else
                [deskCalc divide: value1];
        }
        else if (operator == 'S') {
            [deskCalc set: value1];
        }
        else if (operator == 'E') {
            [deskCalc accumulator];
            program = YES;
        }
        else {
            NSLog (@"Unknown operator");
        }
    }

    NSLog (@"The result is %f", [deskCalc accumulator]);

    [deskCalc release];

    [pool drain];
    return 0;
}


You haven't set the initial value of program, so it defaults to a garbage value which just happens to be non-zero.

Set the initial value of program when you declare it:

BOOL program = NO; // or YES, whichever is appropriate


It is always a good practice to initialize all your variables when you declare them.

Also using scanf for input may be overdoing it, if I were you I would use fgets and then extract the information from the string using strtok. That way even if the user puts his elbow on the keyboard you will not have to worry. Alternatively if you are fond of scanf use sscanf on that string instead of strtok.

0

精彩评论

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