Objective-C ...为什么if语句不起作用?

时间:2013-01-25 13:33:02

标签: objective-c cocoa

#import <Foundation/Foundation.h>

@interface Calculator : NSObject

@property int numerator, denominator;

-(void) print;
-(double) convertToNum;
@end

#import "Calculator.h"

@implementation Calculator

@synthesize numerator, denominator;

-(void) print
{
    NSLog(@"%i/%i", numerator, denominator);
}

-(double) convertToNum
{

    if (denominator != 0)
    {
        return (double) numerator / denominator;
    }
    else
    {
        return 25.68;
    }
}
@end

#import <Foundation/Foundation>
#import "Calculator.h"

int main(int argc, const char * argv[])
{

    Calculator *myCalc = [[Calculator alloc] init];



    @autoreleasepool
    {
        //int numerator, denominator;
        //NSLog(@"Enter two numbers...");
        //scanf("%i %i", &numerator, &denominator);

        [myCalc setNumerator: 8];
        [myCalc setDenominator: 0];
        NSLog(@"The value of myFraction is: ");

        [myCalc convertToNum];
        [myCalc print];
    }
    return 0;
}

由于某种原因,它总是将其作为分数返回。我将它设置为8和0仅作为示例,它返回8/0而不是我选择的随机数来检查else是否正常工作。任何帮助都会很棒。

2 个答案:

答案 0 :(得分:2)

您的convertToNum方法会返回结果,但不会更改对象中的任何状态。因此,对print的调用会打印它的作用,因为从convertToNum返回的值完全被忽略。

将您的print更改为:

-(void) print
{
    NSLog(@"%i/%i = %f", numerator, denominator, [self convertToNum]);
}

答案 1 :(得分:1)

在您的打印方法中,您只是以这种方式打印它:

按照代码中的建议进行更改

-(void) print
{
    //NSLog(@"%i/%i", numerator, denominator);
    NSLog(@"%f", numerator/denominator);
}

[myCalc convertToNum];这个方法有什么价值,但你丢弃了它!

您应该将其用作:

double value=[myCalc convertToNum];
[self print:value];

然后将此value发送给print

-(void) print:(double)value{
        NSLog(@"%f", value);
}