我正在编写我的第一个真正的目标 C 程序,它是为了制作一个非常简单的计算器,就像 Stephen Kochan 的《Objective-C 2.0 编程》一书一样。
无论如何,每当我运行程序时,它只会一遍又一遍地不断打印相同的内容,而没有给我输入其他内容的选项。代码如下,如果有人可以帮助我认为问题出在 while 循环和 switch 函数之间。先感谢您!
#import <Foundation/Foundation.h>
@interface Calculator : NSObject {
double number, accumulator;
char operator;
}
-(void) add: (double) n;
-(void) subtract: (double) n;
-(void) multiply: (double) n;
-(void) divide: (double) n;
@end
@implementation Calculator
-(void) add: (double) n {
accumulator += n;
NSLog(@"%fl", accumulator);
}
-(void) subtract: (double) n {
accumulator -= n;
NSLog(@"%fl", accumulator);
}
-(void) multiply: (double) n {
accumulator *= n;
NSLog(@"%fl", accumulator);
}
-(void) divide: (double) n {
if (n == 0)
NSLog(@"Error! You can't divide by 0!");
else
accumulator /= n;
NSLog(@"%fl", accumulator);
}
@end
int main(int argc, const char * argv[])
{
@autoreleasepool {
double number, accumulator;
char operator;
Calculator *myCalc = [[Calculator alloc] init];
NSLog(@"Begin calculations by typing a number then S");
scanf("%lf, %c", &accumulator, &operator);
while (operator != 'E') {
NSLog(@"%lf", accumulator);
NSLog(@"What would you like to do next?");
scanf("%lf, %c", &number, &operator);
switch (operator) {
case '+':
[myCalc add: number];
break;
case '-':
[myCalc subtract: number];
break;
case '*':
[myCalc multiply: number];
break;
case '/':
[myCalc divide: number];
break;
default:
break;
}
}
}
return 0;
}