Chapter C ++ C ++ programming simple

2.1 C ++ language overview
1, the example program

//2_1.cpp
#include <iostream>
using namespace std;
void main(void)
{
     cout<<"Hello!\n";
     cout<<"Welcome to c++!\n";
}

Operating results:! The Hello
                  is available for purchase to c ++!

2, C ++ character set

Case letters: A ~ Z, a ~ z
numeric characters: 0 ~ 9
! Special characters: the space #% ^ & *   
                   _ (underline) + = - ~ <    
                  > / \ ' ";, () []. {}

3, lexical mark

Categories     C ++ predefined word
identifier     word declared programmer, program text named entities in the
text     using the data represented by the symbol directly in the program
operator     for implementing various operations symbol
separator   () {}, :; is used to separate individual tokens or lexical program text
whitespace     space, tab (TAB key generated character), line feed (Enter key generated character) and the generic name annotation

2.2 Basic data types and expressions

2.2.1 Basic Data Types

2.2.2 Constant 

  • Integer constants: a positive integer, negative integer, zero. Representation are: decimal, octal and hexadecimal
  • Real constant: the general form and exponential form, as 0.345E + 2
  • Character constant: 'a', 'D',, '$' '?'
  • String constants: a pair of double quotes sequence of characters
  • Boolean constants: false and true

2.2.3 Variables

Variable storage types:

  • auto belonging temporary storage, which storage space may be covered with several variables used multiple times.
  • stored in the register in the general register.
  • extern be referenced in all functions and blocks.
  • static fixed address in memory is stored, it is valid for the entire program is running.

2.2.4 symbolic constants

const data type specifier constant name = constant value; 
or
a data type specifier constant name = const constant value;
for example: to declare a symbol representing a constant ratio of the circumference

const float PI= 3.1415926:

Note: Be sure to assign symbolic constant initial statement, and the break in the program can not change its value

2.2.5 operator of the expression

  • The basic mathematical operators + - * / (integer division if the result rounded)% (Remainder operand is an integer)
  • Priority and associativity first multiplication and division, addition and subtraction after, at the same level from left to right
  • ++, - (increment, decrement) Example: i ++; - j;



2, comma comma operator and expressions
formats: Expression 1, Expression 2
Solution sequence and results: First Solution 1, and then Solution 2, the final result is the value of the expression 2
3, and the conditional operator conditional expression:

  • The general form: 1 expression? Expression 2: Expression 3 (expression 1 must be bool type) Example: x = a> b a: b;?
  • The order of execution:
    • First solving expression 1,
    • If an expression evaluates to true, then the final result is solving Expression 2, Expression 2
    • If an expression is false, then solving Expression 3, the value of the final result of the expression 3

Note: conditional operator excellent level higher than the assignments, below the logical operator
. 4, sizeof operator
syntax sizeof (type name) or sizeof expressions
result value: "type name" of the type specified or "expression" the result type the number of bytes occupied .
example:

sizeof(short)
sizeof(x)

7-bit computing

  • & Bitwise and: the two operands respectively corresponding to each of a logical AND operation.
    • use:
    • The position of a 0, the other bits unchanged.
    • To take the specified position.
  • | Bitwise or: each bit respectively corresponding to the logical OR of two operands.
    • Uses: certain position 1, the other bits unchanged.
  • Bitwise XOR ^: each bit corresponding to two operands is exclusive or specific computing rule is: If the corresponding bit of the same, the bit operation result is 0; if the corresponding bits are different, the bit operation result 1.
    • Uses: a specific bit flip (the XOR 0 is asserted, the negated XOR 1)
  • Bitwise ~: bitwise is a unary operator, the role is a binary number each bit of the inverse
  • << left shift operation: the left, low fill 0, give up high
  • A right shift operation >>: the right, lower: Discard; High: unsigned number: complement signed numbers 0: complement "sign bit"

8, operator precedence and associativity

9, conversion of mixed data types: Type Operand if inconsistency involved in computing the arithmetic and relational operators, the compiler will automatically convert the data (i.e., implicit conversion)

  • Implicit conversion: low-high type data into the data type
    • This conversion is safe, because there is no loss of accuracy in the data conversion process.
  • Explicit conversion: casts
    • Syntax: type specifier (expression) or (type specifier) ​​Expression

2.2.6 Statement

Input and output data 2.3

2.3.1 I/O流
插入操作。数据的输入与输出是通过I/O流来实现的,cin和cout是预定义的流类对象。
cin 用来处理标准输入,即键盘输入。
cout 用来处理标准输出,即屏幕输出。

2.3.2 预定义的插入符和提取符
cout    流插入运算符 <<
cin   流提取运算符 >> 

#include <iostream>
 
using namespace std;
int main( )
{
   char name[50];
 
   cout << "请输入您的名称: ";
   cin >> name;
   cout << "您的名称是: " << name << endl;
}

endl 用于在行末添加一个换行符
流插入运算符 <<  和 流提取运算符 >> 在一个语句中可以多次使用,如上面实例中所示。

2.4 算法的基本控制

算法的基本控制结构有3种:顺序结构、选择结构和循环结构。
2.4.1 if 语句
三种形式

if   (表达式)   语句
例:if  (x>y)  cout<<x;

if   (表达式)   语句1  else  语句2
例:if  (x>y)  cout<<x;
             else  cout<<y;

if   (表达式1)  语句1
    else  if  (表达式2)  语句2
    else  if  (表达式3)  语句3
           …
    else  语句 n

2.4.2 多重选择结构

#include<iostream>
using namespace std;
void main()
{
    int x,y;
    cout<<"Enter x and y:";
    cin>>x>>y;
    if (x!=y)
        if (x>y)
            cout<<"x>y"<<endl;
        else
            cout<<"x<y"<<endl;
    else
        cout<<"x=y"<<endl;

if语句嵌套 一般形式:

if  (   )
     if  (   )    语句 1
     else   语句 2
else
     if  (   )    语句 3
     else   语句 4
注意:语句 1、2、3、4 可以是复合语句,每层的 if 与 else 配对,或用 { } 来确定层次关系。

 

//输入一个0~6的整数,转换成星期输出。

#include <iostream>
using namespace std;
void main(void)
{	int day;
	cin >> day;
	switch (day)
	{	
	 	case 0:	cout << "Sunday" << endl;    break;
	 	case 1:	cout << "Monday" << endl;   break;
		case 2:	cout << "Tuesday" << endl;   break;
		case 3:  cout << "Wednesday" << endl;   break;
	 	case 4:	cout << "Thursday" << endl;   break;
	 	case 5:	cout << "Friday" << endl;   break;
	 	case 6:	cout << "Saturday" << endl;   break;
	 	default:	      cout << "Day out of range Sunday .. Saturday" << endl;
					break;
	 }
}

一般形式:
switch  (表达式)
   {  case    常量表达式 1:语句1
      case    常量表达式 2:语句2
                  ┆
      case    常量表达式 n:语句n
      default :             语句n+1
   }
执行顺序:case中的常量表达式值为入口标号,由此开始顺序执行。因此,每个case分支最后应该加break语句。
注意问题:

  • case分支可包含多个语句,且不用{ }。
  • 表达式、判断值都是int型或char型。
  • 若干分支执行内容相同可共用一组语句。

2.4.3 循环结构与选择
形式:    while  (表达式)  语句

//求自然数1~10之和
#include<iostream>
using namespace std;
void main()
{
  int i(1), sum(0);
  while(i<=10)
  {
      sum+=i;  //相当于sum=sum+i;
      i++;
  }
  cout<<"sum="<<sum<<endl;
}

do   语句
while (表达式)

//输入一个整数,将各位数字反转后输出。
#include <iostream>
using namespace std;
void main(void)
{
	int n, right_digit, newnum = 0; 
	cout << "Enter the number: ";
	cin >> n;
	
	cout << "The number in reverse order is  ";
	do
	{
		right_digit = n % 10;
		cout << right_digit;
		n /= 10;  //相当于n=n/10
	} 
	while (n != 0);
  cout<<endl;		
}

语法形式:
for  (表达式1;表达式2;表达式3)  语句

#include <iostream>
using namespace std;
void main(void)
{ 
	int n, k;

	cout << "Enter a positive integer: ";
	cin >> n;
	cout << "Number  " << n << "   Factors  ";

	for (k=1; k <= n; k++)
		if (n % k == 0)
			cout << k << "  ";
  cout << endl;
}

例题:编写程序输出以下图案
                        *
                      ***
                    *****
                  *******
                  *****
                  ***
                  *

#include<iostream>
using namespace std;
void main()
{  int i,j,n=4;
   for(i=1;i<=n;i++)  //输出前4行图案
   { for(j=1;j<=30;j++)
       cout<<' ';  //在图案左侧空30列
     for(j=1; j<=8-2*i ;j++)
       cout<<' ';
     for(j=1; j<=2*i-1 ;j++)
       cout<<'*';
     cout<<endl;
   }
for(i=1;i<=n-1;i++)  //输出后3行图案
   { for(j=1;j<=30;j++)
       cout<<' ';  //在图案左侧空30列
     for(j=1; j<=7-2*i ;j++)
       cout<<'*';
     cout<<endl;
   }
}

循环结构与选择结构的嵌套

#include<iostream>
using namespace std;
void main()
{   
	int n;
	for(n=100; n<=200; n++)
	{    if (n%3!=0)
	     cout<<n;
	}
}

例题:读入一系列整数,统计出正整数个数i和负整数个数j,读入0则结束。

#include<iostream>
using namespace std;
void main()
{ int  i=0, j=0, n;
  cout<<"请输入若干整数(输入0则结束):";
  cin>>n;
  while(  n!=0  )
  {  if(n>0) i++;
     if(n<0) j++;
     cin>>n    ;
  }
  cout<<"正整数个数:"<<i<<"   负整数个数:"<<j<<endl;
}


2.4.5 其他控制语句
break语句
使程序从循环体和switch语句内跳出,继续执行逻辑上的下一条语句。不宜用在别处。
continue 语句
结束本次循环,接着判断是否执行下一次循环


2.5 自定义数据类型
2.5.1 typedef
为一个已有的数据类型另外命名
语法形式 typedef  已有类型名  新类型名表;
例如
typedef double area,volume;
typedef int natural;
natural i1,i2;
area a;
volume v;

2.5.2 枚举类型enum
枚举类型应用说明:

  • 对枚举元素按常量处理,不能对它们赋值。例如,不能写:sun=0;
  • 枚举元素具有缺省值,它们依次为: 0,1,2,......。
  • 也可以在声明时另行指定枚举元素的值,如:
  • enum weekday {sun=7,mon=1,tue,wed,thu,fri,sat};
  • 枚举值可以进行关系运算。
  • 整数值不能直接赋给枚举变量,如需 要将整数赋值给枚举变量,应进行强 制类型转换。


例子:设某次体育比赛的结果有四种可能:胜(win)、负(lose)、平局(tie)、比赛取消(cancel),编写程序顺序输出这四种情况。

#include <iostream>
using namespace std;
enum game_result {WIN, LOSE, TIE, CANCEL};
int main()
{ game_result result;
   enum game_result omit = CANCEL;
   int count;
   for (count = WIN ; count <= CANCEL ; count++) 
   { result = (game_result)count;
      if (result == omit)
      {    cout << "The game was cancelled\n";      }
      else 
      { cout << "The game was played ";
         if (result == WIN)         cout << "and we won!";
         if (result == LOSE)       cout << "and we lost.";
         cout << "\n";
      }
   }
   return 0;
}


2.5.3 结构体 - 结构的声明
结构:是由不同数据类型的数据组成的集合体
  struct  结构名
  {
      数据类型   成员名 1;
      数据类型   成员名 2;
       ……
      数据类型   成员名 n; 
  };
举例:

struct student   //学生信息结构体
{
    int num;  //学号
    char name[20];  //姓名
    char gender;  //性别
    int age;  //年龄
    float score;  //成绩
    char addr[30];  //住址
}

结构体变量形式: 
   结构名  结构变量名;

注意:

  • 结构变量的存储类型概念、它的寿命、可见性及使用范围与普通变量完全一致。
  • 结构变量说明在结构类型声明之后,二者也可同时进行。
  • 结构变量占内存大小可用 sizeof 运算求出: sizeof(运算量)

初始化:    说明结构变量的同时可以直接设置初值。
使用:   结构体成员的引用形式:      结构变量名.成员名

结构体变量的初始化和使用
#include <iostream>
#include <iomanip>
using namespace std;
struct student   //学生信息结构体
{  int num;  //学号
    char name[20];  //姓名
    char gender;  //性别
    int age;  //年龄
}stu={97001,"Lin Lin",'F',19};
void main()
{  cout<<setw(7)<<stu.num<<setw(20)<<stu.name       <<setw(3)<<stu.sex<<setw(3)<<stu.age;
}

2.54 联合体
union 联合名
  {
      数据类型   成员名 1;
      数据类型   成员名 2;
      ……
      数据类型   成员名 n; 
  };
例子:

 union uarea
{  char   c_data;
   short  s_data;
   long   l_data;
}

2.54 无名联合体
无名联合没有标记名,只是声明一个成员项的集合,这些成员项具有相同的内存地址,可以由成员项的名字直接访问。
例:
union
{    int    i;
     float   f;
}
在程序中可以这样使用:
i=10;
f=2.2;




 

Guess you like

Origin www.cnblogs.com/alec7015/p/12380073.html