使用静态变量对类中的值求和,以获得输出,Objective-C

时间:2014-09-01 03:05:28

标签: objective-c variables static

Objective-C的新手,并且我已经使用类/方法在两个不同的课程中输出学生的值。

这是一个简单的部分,我需要帮助的部分是如何声明一个静态变量并使用这个变量将所有学生的值加在一起并输出值。

我已经看过各种各样的例子和线索,而且我真的试图将它放在这一点上,但我无法弄清楚如何应用这个问题的概念。用另一种语言很容易做到但与ObjC不一样......

代码如下:

//
//  main.m
//  yadda yadda
//
//  Created by yadda yadda on 8/26/14.
//  Display the number of students in two different courses.
//
//  Copyright (c) 2014 yadda.self. All rights reserved.
//

#import <Foundation/Foundation.h>


//---- @interface section ----

@interface Students: NSObject

-(void) setCourseOne: (int) a;
-(void) setCourseTwo: (int) b;
-(int) courseone;
-(int) coursetwo;

@end

//---- @implementation section ----

@implementation Students
{
    int courseone;
    int coursetwo;
}

-(void) setCourseOne:(int) a
{
    courseone = a;
}

-(void) setCourseTwo:(int) b
{
    coursetwo = b;
}

-(int) courseone
{
    return courseone;
}

-(int) coursetwo
{
    return coursetwo;
}

@end

//---- Program section ----


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

    @autoreleasepool {

       Students *myStudents = [[Students alloc] init];

       [myStudents setCourseOne: 8];
       [myStudents setCourseTwo: 24];

        NSLog(@"There are %i students in this class", [myStudents courseone]);
        NSLog(@"There are %i students in this class", [myStudents coursetwo]);

        //Third output statement for sum of all students
        NSLog(@"There are %i students in all of the classes", [myStudents courseone]);
    }
    return 0;
}

1 个答案:

答案 0 :(得分:0)

你尝试过简单的添加吗?

NSLog(@"There are %i students in all of the classes", [myStudents courseone]+[myStudents coursetwo]);

如果您想使用 local 变量,可以使用:

int total = [myStudents courseone] + [myStudents coursetwo];
NSLog(@"There are %i students in all of the classes", total);

还有其他一些评论可以用来改进您的代码,但是当您按照作业进行操作时,我们会假设您将按照您的进度来做这些事情。

HTH