循环结构与选择结构

作者:追风剑情 发布于:2019-2-20 16:55 分类:Objective-C

与C语言相同

for(){}

while{}

do{} while()

if(){}else{}

switch

condition ? expression1 : expression2

示例一:键盘输入

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        int n, number, triangularNumber;
        
        NSLog(@"What triangular number do you want?");
        // 接受一个从键盘输入的数字赋给number变量
        scanf("%i", &number);
        
        triangularNumber = 0;
        
        for (n=1; n<=number; ++n)
            triangularNumber += n;
        
        NSLog(@"Triangular number %i is %i\n", number, triangularNumber);
    }
    return 0;
}

运行测试

111.png

示例二:从终端输入字符

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        char c;
        
        NSLog (@"Enter a single character:");
        //前面加个空格,使scanf函数跳过输入中的空白字符(例如,换行、回车、制表符...)
        scanf (" %c", &c);
        
        if ( (c >='a' && c <= 'z') || (c >= 'A' && c <= 'Z') )
            NSLog(@"It's an alphabetic character.");
        else if ( c >= '0' && c <= '9')
            NSLog(@"It's a digit.");
        else
            NSLog(@"It's a special character.");
    }
    return 0;
}

运行测试
22222.png


标签: Objective-C

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号