已声明但未设置的变量评估为真? [英] Declared but unset variable evaluates as true?

查看:52
本文介绍了已声明但未设置的变量评估为真?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用下面的代码做一个简单的计算器.现在它完美地执行.然而,当我试图改变周围的东西时,它不起作用.我使用 BOOL 程序 来检查是继续询问该人的输入还是完成程序.

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.

如果我将 while 语句的表达式更改为只是 (program) 并将 YES/NO 更改为program 语句,为什么代码无法执行 while 中的内容?

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;
}

推荐答案

你还没有设置program的初始值,所以它默认是一个垃圾值,只是发生em> 为非零.

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

在声明时设置program的初始值:

Set the initial value of program when you declare it:

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

这篇关于已声明但未设置的变量评估为真?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆