我正在寫我的第一個真正的客觀C程序,它是一本非常簡單的計算器,就像Stephen Kochan編寫的Objective-C 2.0中的一本書。簡單的Objective-C計算器程序不斷打印
無論如何,無論何時,只要我運行該程序,它只是不斷地重複打印相同的東西,而不是給我輸入其他東西的選項。代碼如下,如果有人可以幫助,我認爲這個問題是介於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;
}
嘗試把這些放在你的while的末尾:NSLog(@「你下一步要做什麼?」); scanf(「%lf,%c」,&number,&operator);這將導致程序停止,一旦它到達這些,而不是經常 – user2277872
我不知道我是如何錯過了!但不幸的是,它仍在繼續運行,我不知道爲什麼...... –
@AshleyElisabethStallings呃,所以我不知道我以前的評論已經消失了,但讓我重複一遍:我建議你在試着從Objective-C開始(包括關於C標準庫的知識,不僅僅是語言),否則你會在以後遇到麻煩。 – 2013-07-14 05:45:02