Exercise:
“Complex numbers are numbers that contain two components: a real part and an
imaginary part. If a is the real component and b is the imaginary component, this
notation is used to represent the number:
a + b i
Write an Objective-C program that defines a new class called Complex. Following
the paradigm established for the Fraction class, define the following methods for
your new class:
-(void) setReal: (double) a;
-(void) setImaginary: (double) b;
-(void) print; // display as a + bi
-(double) real;
-(double) imaginary;
Write a test program to test your new class and methods.”
Here is my solution that doesn’t work:
#import <Foundation/Foundation.h>
@iterface Complex:NSObject
{
double a, b;
}
-(void)setReal: (double) a;
-(void)setImaginary: (double) b;
-(void) print;
-(double) real;
-(double) imaginary;
@end
@implementation Complex
-(void)setReal
{
scanf(@"Set real value %f",&a);
}
-(void)setImaginary
{
scanf(@"Set imaginary value %f", &b);
}
-(void) print
{
Nslog(@"Your number is %f",a+bi);
}
-(double)real
{
Nslog(@"Real number is %f",a);
}
-(double)imaginary
{
NSlog(@"Imaginary number is %f",b)
}
@end
int main (int argc, char *argv[])
{
NSAutoreleasePool *pool=[[NSAutoreleasePool alloc] init];
Complex*num=[[complex alloc] init];
[num setReal:3];
[num setImaginary:4];
Nslog(@"The complex number is %i",[num print]);
[num release];
[pool drain];
return 0;
}
Please, what is wrong?
There are a few obvious flaws that I can see. First, (and this may be a copy/paste error), you misspelled
interfaceasiterface.Second, your
printmethod does not write to the NSLog correctly. You’re trying to force an expressiona+bias the result to the format specifier%f. Instead, you’ll want to have two arguments, with bothaandbbeing passed separately to the NSLog call. Thus you’d have:Lastly, your methods
realandimaginaryare supposed to be ‘getters’ for your instance variables, not functions that print to NSLog. Thus, you’ll instead just want the function bodies to bereturn a;andreturn b;respectively. For the former (in full):