Declared but unset variable evaluates as true?(已声明但未设置的变量评估为真?)
问题描述
我正在用下面的代码做一个简单的计算器.现在它完美地执行.然而,当我试图改变周围的东西时,它不起作用.我使用 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
这篇关于已声明但未设置的变量评估为真?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:已声明但未设置的变量评估为真?
 
				
         
 
            
        - Android - 我如何找出用户有多少未读电子邮件? 2022-01-01
- 在测试浓缩咖啡时,Android设备不会在屏幕上启动活动 2022-01-01
- 使用自定义动画时在 iOS9 上忽略 edgesForExtendedLayout 2022-01-01
- android 4中的android RadioButton问题 2022-01-01
- Android - 拆分 Drawable 2022-01-01
- Android viewpager检测滑动超出范围 2022-01-01
- 想使用ViewPager,无法识别android.support.*? 2022-01-01
- 用 Swift 实现 UITextFieldDelegate 2022-01-01
- 如何检查发送到 Android 应用程序的 Firebase 消息的传递状态? 2022-01-01
- MalformedJsonException:在第1行第1列路径中使用JsonReader.setLenient(True)接受格式错误的JSON 2022-01-01
 
				 
				 
				 
				