数组

作者:追风剑情 发布于:2019-2-26 14:41 分类:Objective-C

示例

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // 生成前15个斐波那契数
        int Fibonacci[15], i;
        
        Fibonacci[0] = 0;
        Fibonacci[1] = 1;
        
        for (i = 2; i < 15; ++i)
            Fibonacci[i] = Fibonacci[i-2] + Fibonacci[i-1];
        
        for (i = 0; i < 15; ++i)
            NSLog(@"%i", Fibonacci[i]);
        
        // 声明数组的同时赋初值
        int itegers[5] = {0, 1, 2, 3, 4};
        char letters[5] = {'a', 'b', 'c', 'd', 'e'};
        // 只对前三个元素赋初值,其余元素默认为0
        float sample_data[500] = {100.0, 300.0, 500.5};
        // 对指定索引元素赋初值
        int x = 1233;
        int a[] = {[9] = x + 1, [2] = 3, [1] = 2, [0] = 1};
        
        // 定义字符串,注意要以\0结尾
        char world[] = {'H', 'e', 'l', 'l', 'o', '!', '\0'};
        NSLog(@"world=%s", world);
        
        // 定义并初始化二维数组
        int M[4][5] = {
            {10, 5, -3, 17, 82},
            {9, 0, 0, 8, -7},
            {32, 20, 1, 0, 14},
            {0, 0, 8, 7, 6}
        };
        
        // 二维数组内层大括号可以省略,会自动按行初始化
        int N[4][5] = { 10, 5, -3, 17, 82, 9, 0, 0, 8, -7, 32,
            20, 1, 0, 14, 0, 0, 8, 7, 6 };
        
        // 不必初始化整个二维数组元素
        int K[4][5] = {
            {10, 5, -3},
            {9, 0, 0},
            {32, 20, 1},
            {0, 0, 8}
        };
    }
    return 0;
}

运行测试
111.png

标签: Objective-C

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号