Code: (Objective-C)
- // Chapter 4 Exercise 6.
- // 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+bi
- //
- // 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.
- #include <Foundation/Foundation.h>
- @interface Complex : NSObject
- -(void) setReal: (double) a;
- -(void) setImaginary: (double) b;
- -(void) print; // display as a + bi
- -(double) real;
- -(double) imaginary;
- @end
- @implementation Complex
- {
- double real, imaginary;
- }
- -(void) setReal: (double) a
- {
- real = a;
- }
- -(void) setImaginary: (double) b
- {
- imaginary = b;
- }
- -(void) print
- {
- NSLog(@"%f + %fi", real, imaginary);
- }
- -(double) real
- {
- return real;
- }
- -(double) imaginary
- {
- return imaginary;
- }
- @end
- int main(int argc, const char *argv[]) {
- @autoreleasepool {
- Complex *myComplex = [[Complex alloc]init];
- [myComplex setReal: 5];
- [myComplex setImaginary: 10];
- [myComplex print];
- }
- return 0;
- }
Output:
5.000000 + 10.000000i