学习《C++ Primer Plus》04

处理数据

1.简单变量

把信息存储在计算机中,程序必须记录三个基本属性:

  1. 信息将存储到哪里;
  2. 要存储什么值;
  3. 存储何种类型的信息。

变量名的命名规则:

  1. 在名称中只能使用字母字符、数字和下划线(-);
  2. 名称的第一个字符不能是数字;
  3. 区分大写字符和小写字符;
  4. 不能将C++关键字用作名称;
  5. 以两个下划线或下划线和大写字母打头的名称被保留给实现(编译器及其使用资源)使用,一个下划线开头的名称保留给实现,用作全局标识符;
  6. C++对与名称的长度没有限制,名称中所有的字符都有意义,但有些平台有长度限制。

命名方案:

函数名最好有代表意义,例如my_eye_tooth,myEyeTooth;加上前缀表示变量类型,例如nweight,n表示整数值;还有其他前缀如:str或sz(表示以空字符结尾的字符串)、b(布尔值)、p(指针)和c(单个字符)。

  1. 整型

一般情况下,char8位,short16位,int32位,long32位,long long64位

可利用运算符sizeof()和头文件limits查看系统每种类型的位数及取值范围:

//limits.cpp--some integer limits

#include<iostream>

#include<climits>

using namespace std;

 

int main()

{

    int n_int = INT_MAX;

    short n_short = SHRT_MAX;

    long n_long = LONG_MAX;

    long long n_llong = LLONG_MAX;

 

    //sizeof operator yiulds size of type or of variable

    cout << "int is " << sizeof(int) << " bytes." << endl;

    cout << "short is " << sizeof n_short<< " bytes." << endl;

    cout << "long is " << sizeof n_long<< " bytes." << endl;

    cout << "long long is " << sizeof n_llong << " bytes." << endl;

    cout << endl;

 

    cout << "Maximum values: " << endl;

    cout << "int: " << n_int << endl;

    cout << "short:po= " << n_short << endl;

    cout << "long: " << n_long << endl;

    cout << "long long: " << n_llong << endl;

    cout << "Minimum int value = " << INT_MIN << endl;

    cout << "Bits per type = " << CHAR_BIT << endl;

    cin.get();

    return 0;

}

 

2.const限定符

不同于C语言的#define,C++利用const处理符号常量。

 

3.浮点数

一般float32位,double64位,long double80-128位。float只有六位精度。之所以称为浮点,就是因为小数点可移动,例如d.dddE+n,指的是将小数点左移n位。

通常cout会删除结尾的零,调用cout.setf()将覆盖这种行为。

 

4.C++运算符

+、—、*、\、%(运算符求模,两个操作数必须是整数)。

 

5.类型转换

  1. 将一种算术类型的值赋给另一种算术类型的变量时,C++将对值进行转换;
  2. 表达式中包含不同的类型时,C++将对值进行转换;
  3. 将参数传递给函数时,C++将对值进行转换。

 

猜你喜欢

转载自blog.csdn.net/ly_222222/article/details/81096746