声明未设置但是变量计算结果为真? [英] Declared but unset variable evaluates as true?
问题描述
我在做有以下code一个简单的计算器。现在它完美地执行。当我试图改变周围的事物,但是,这是行不通的。我用 BOOL程序
来检查是否继续要求输入由人或完成计划。
如果我改变前$ P $ ,而
pssion声明只是(程序)
和变更是
/ NO
在程序
语句,为什么用code不能做的是里面的,而
?
//一个简单的印刷计算器
{
NSAutoreleasePool *池= [[NSAutoreleasePool的alloc]初始化]
计算器* deskCalc = [[计算器的alloc]初始化];
双值1;
焦炭运营商
BOOL程序; [deskCalc setAccumulator:0]; 而(!程序){
的NSLog(@请输入你的前pression);
scanf函数(%LF%C,&安培;值1,和放大器;运营商);
程序= NO; 如果(==操作符'+'){
[deskCalc添加:值1];
}
否则,如果(==操作符' - '){
[deskCalc减:值1];
}
否则,如果(==操作符'*'||运算符=='X'){
[deskCalc乘法:值1];
}
否则,如果(操作符=='/'){
如果(值== 0)
的NSLog(@除以零!);
其他
[deskCalc鸿沟:值1];
}
否则,如果(==操作符'S'){
[deskCalc设置:值1];
}
否则,如果(操作员=='E'){
[deskCalc蓄电池]
程序= YES;
}
其他{
的NSLog(@未知运营商);
}
} 的NSLog(@结果是%F,[deskCalc蓄电池]); [deskCalc发布] [池排水]
返回0;
}
您还没有设置的程序
,所以它默认为一个垃圾值初始值只发生的是非零
设置的初始值程序
,当你把它声明:
BOOL程序= NO; //或YES,较合适
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屋!