“sigma 表示法是求和的简写。它在这里的使用意味着将 1/2^i 的值相加,其中 i 从 1 变化到 n。也就是说,添加 1/2 + 1/4 + 1/8 .. .. 如果你使 n 的值足够大,这个系列的总和应该接近 1。让我们尝试不同的 n 值,看看我们有多接近。
#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;
-(Fraction*) add: (Fraction *) f;
-(void) reduce;
@end
#import "Fraction.h"
@implementation Fraction
@synthesize numerator, denominator;
-(void) print
{
NSLog (@"%i/%i", numerator, denominator);
}
-(void) setTo: (int) n over: (int) d
{
numerator = n;
denominator = d;
}
-(Fraction *) add: (Fraction *) f
{
// To add two fractions:
// a/b + c/d = ((a*d) + (b*c)) / (b * d)
// result will store the result of the addition
Fraction *result = [[Fraction alloc] init];
result.numerator = numerator * f.denominator +
denominator * f.numerator;
result.denominator = denominator * f.denominator;
[result reduce];
return result;
}
#import "Fraction.h"
int main (int argc, char *argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
Fraction *aFraction = [[Fraction alloc] init];
Fraction *sum = [[Fraction alloc] init], *sum2;
int i, n, pow2;
[sum setTo: 0 over: 1]; // set 1st fraction to 0
NSLog (@"Enter your value for n:");
scanf ("%i", &n);
pow2 = 2;
for (i = 1; i <= n; ++i) {
[aFraction setTo: 1 over: pow2];
sum2 = [sum add: aFraction];
[sum release]; // release previous sum
sum = sum2;
pow2 *= 2;
}
NSLog (@"After %i iterations, the sum is %g", n, [sum convertToNum]);
[aFraction release];
[sum release];
[pool drain];
return 0;
}
问题:为什么我们必须创建在“for”循环中使用的附加变量 sum2?为什么我们需要在这里“释放先前的总和”,然后再给它一个我们刚刚释放的值?:
sum2 = [sum add: aFraction];
[sum release]; // release previous sum
sum = sum2;
难道只是为了避免内存泄漏?(方法“add”初始化一个存储在 sum2 中的变量)