尝试在Fraction操作上编写简单程序。 无法编译代码。在“减去”方法的界面中获得“预期标识符或'('xcode'错误。
我对这个问题进行了研究,在我看来,这是一种通用错误。 这是我的计划:
#import <Foundation/Foundation.h>
// Define the Fraction class
@interface Fraction : NSObject
{
int numerator;
int denominator;
}
@property int numerator, denominator;
-(void) print;
-(void) setTo: (int) n over: (int) d;
-(double) convertToNum;
-(Fraction *) add: (Fraction *) f;
–(Fraction *) subtract: (Fraction *) f;
–(Fraction *) multiply: (Fraction *) f;
–(Fraction *) divide: (Fraction *) f;
-(void) reduce;
@end
#import "Fraction.h"
@implementation Fraction
@synthesize numerator, denominator;
-(void) print
{
NSLog (@"%i/%i", numerator, denominator);
}
-(double) convertToNum
{
if (denominator != 0)
return (double) numerator / denominator;
else
return NAN;
}
-(void) setTo: (int) n over: (int) d
{
numerator = n;
denominator = d;
}
// add a Fraction to the receiver
-(Fraction *) add: (Fraction *) f
{
Fraction *result = [[Fraction alloc] init];
result.numerator = numerator * f.denominator +
denominator * f.numerator;
result.denominator = denominator * f.denominator;
[result reduce];
return result;
}
-(Fraction *) subtract: (Fraction *) f
{
Fraction *result = [[Fraction alloc] init];
result.numerator = numerator * f.denominator -
denominator * f.numerator;
result.denominator = denominator * f.denominator;
[result reduce];
return result;
}
-(Fraction *) multiply: (Fraction *) f
{
Fraction *result= [[Fraction alloc] init];
result.numerator = numerator * f.numerator;
result.denominator = denominator * f.denominator;
[result reduce];
return result;
}
-(Fraction *) divide: (Fraction *) f;
{
Fraction *result = [[Fraction alloc] init];
result.numerator= numerator * f.denominator;
result.denominator = denominator * f.numerator;
[result reduce];
return result;
}
-(void) reduce
{
int u = numerator;
int v = denominator;
int temp;
while (v != 0) {
temp = u % v;
u = v;
v = temp;
}
numerator /= u;
denominator /= u;
}
@end
#import "Fraction.h"
int main (int argc, char *argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
Fraction *myFraction1 = [[Fraction alloc] init];
Fraction *myFraction2 = [[Fraction alloc] init];
[myFraction2 setTo:200 over:300];
[myFraction1 setTo: 100 over: 300];
[myFraction2 subtract: myFraction1];
NSLog (@"The value of myFraction2 is:");
[myFraction2 print];
[myFraction2 release];
[myFraction1 release];
[pool drain];
return 0;
}
答案 0 :(得分:2)
在main
:
Fraction *myFraction2 = [[Fraction alloc] init], ;
答案 1 :(得分:0)
假设这是一个文字复制和粘贴,你使用了错误的破折号。最后在英国和美国的键盘上,你想要的是在'0'键的右侧。您似乎正在使用en-dash。如果您仔细查看上面的商家信息,特别是顶部列表中的add:
与subtract:
,您会看到您的角色稍微宽一点。
尝试复制并粘贴此内容:
-(Fraction *) subtract: (Fraction *) f;
在您现有的定义中看到差异。