[学习笔记—Objective-C]《Objective-C 程序设计 第6版》第四章 数据类型和表达式

本章内容相对比较基础,容易理解。过于简单繁琐的内容在此不再赘述。这里只讲解本章的框架和比较重要的细节部分。

Part1. 数据类型和常量

基本数据类型

  • int:
    • 值域和运行计算机的硬件设置有关
    • NSLog转化字符:%i
  • float:
    • 存储包含小数位的值
    • 科学技术法表示1700:1.7e4
    • NSLog转化字符:%f或者%g
  • double:
    • 与float类型非常相似
    • double的变量可存储的范围大约是float的两倍
  • char:
    • 存储单个字符
    • 合法的字符常量:‘a’,‘2’,‘;’‘\n’:换行符
    • NSLog转化字符:%c

四种基本数据类型的例子
#import <Foundation/Foundation.h>

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

        int integerVar = 100;
        float floatinVar = 245.36;
        double doubleVar = 8.45e+12;
        char charVar = 'R';

        NSLog(@"\nintegerVar = %i", integerVar);
        NSLog(@"\nfloatinVar = %f", floatinVar); 
        NSLog(@"\ndoubleVar = %e", doubleVar);
        NSLog(@"\ndoubleVar = %g", doubleVar);
        NSLog(@"\ncharVar = %c", charVar);        
    }
    return 0;
}

限定词

  • long: 变量的具体范围也是由计算机系统决定的
    • long int counter;十进制格式显示:%li
  • long long:比long具有更大的范围
  • short:考虑有限的内存空间
  • unsigned:只用来存储正数
  • signed

id 类型

  • 存储任何类型的对象
  • 多态和动态绑定的基础

Part 2. 算术表达式

整数运算和一元负号运算符

  • 两个int型数值的运算结果为int型。如有小数点,则取整数部分。结果造成数据丢失。为避免,先强制转换成浮点型再运算。
  • 一元负号运算符:-
    • c = -a * b; 将执行-a*b;

模运算符

  • % 只用于处理正数
  • 跟乘除法的优先级相等

整型值和浮点值的相互转换

#import <Foundation/Foundation.h>

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

        float f1 = 153.135, f2;
        int i1, i2 = -100;

        i1 = f1; //浮点到整数的转换
        NSLog(@"\n%f assigned to an int produces %i", f1, i1);

        f1 = i2; //整数到浮点数的转换
        NSLog(@"\n%i assigned to an float produces %f", i2, f1);

        f1 = i2/100; //整数除以整数
        NSLog(@"\n%i divided by 100 produces %f", i2, f1);

        f2 = i2; //整数除以浮点数
        NSLog(@"\n%i divided by 100。0 produces %f", i2, f2);

        f2 = (float) i2 / 100; //浮点到整数的转换
        NSLog(@"\n(float)%i divided by 100 produces %f", i2, f2);

    }
    return 0;
}

153.134995 assigned to an int produces 153
-100 assigned to an float produces -100.000000
-100 divided by 100 produces -1.000000
-100 divided by 100。0 produces -100.000000
(float)-100 divided by 100 produces -1.000000

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值