C++是一种可用于创建高性能应用程序的跨平台语言。它是由Bjarne Stroustrup开发的,是对C语言的扩展。该语言在2011年,2014年和2017年进行了3次重大更新,分别更新为C++ 11,C++ 14和C++ 17。
为什么要使用C++?
- C++是世界上最受欢迎的编程语言之一。
- 在当今的操作系统,图形用户界面和嵌入式系统中都可以找到C++。
- C++是一种面向对象的编程语言,为程序提供了清晰的结构,并允许代码被重用,从而降低了开发成本。
- C++是可移植的,可用于开发可适应多种平台的应用程序。
- C++有趣且易于学习!
- 由于C++接近C#和Java,因此程序员可以轻松地切换到C++,反之亦然。
C++基本程序
C++
// C++ Hello World Program
#include
using namespace std;
int main()
{
cout << "Hello World!\n";
return 0;
}
C++
// C++ program to implement
// standard output
#include
using namespace std;
int main()
{
cout << "Geeks For Geeks";
return 0;
}
C++
// C++ program to implement
// standard input
#include
using namespace std;
int main()
{
int a;
cout << "Enter a number" << endl;
// User can input an integer
cin >> a;
cout << "User entered number " << a << endl;
}
C++
// C++ program to implement
// data types
#include
using namespace std;
int main()
{
cout << "Size of bool is: " <<
sizeof(bool) <<
" bytes" << endl;
cout << "Size of char is: " <<
sizeof(char) <<
" bytes" << endl;
cout << "Size of int is: " <<
sizeof(int) <<
" bytes" << endl;
cout << "Size of short int is: " <<
sizeof(short int) <<
" bytes" << endl;
cout << "Size of long int is: " <<
sizeof(long int) <<
" bytes" << endl;
cout << "Size of signed long int is: " <<
sizeof(signed long int) <<
" bytes" << endl;
cout << "Size of unsigned long int is: " <<
sizeof(unsigned long int) <<
" bytes" << endl;
cout << "Size of float is: " <<
sizeof(float) <<
" bytes" << endl;
cout << "Size of double is: " <<
sizeof(double) <<
" bytes" << endl;
cout << "Size of wchar_t is: " <<
sizeof(wchar_t) << " bytes" << endl;
return 0;
}
C++
// C++ program to implement
// derived data types
#include
using namespace std;
// Function definition
int sum(int n1, int n2)
{
return n1 + n2;
}
int main()
{
// array declaration and
// initialization
int arr[5] = {2, 4, 6, 8, 10};
cout << "Array elements are : ";
for (int i = 0; i < 5; i++)
{
// printing array elements
cout << arr[i] << " ";
}
// pointers
int a = 10;
// Declared a pointer of
// type int
int* p;
// Pointer p points the address
// of a
p = &a;
cout << "\n" << "Value of a is " <<
a << endl;
// address of a will be printed
cout << "Value of p is " << p <<
endl;
// value of a will be printed
cout << "Value of *p is " << *p <<
endl;
// function calling from main
cout << "Sum is:" << sum(5, 2) <<
endl;
// reference
int x = 10;
int& ref = x;
// Value of x is now changed
// to 30
ref = 30;
cout << "x = " << x << endl;
// Value of x is now changed
// to 40
x = 40;
cout << "ref = " << ref << endl;
return 0;
}
C++
// C++ program to implement
// user-defined data types
#include
using namespace std;
class GFG
{
public:
string gfg;
void print()
{
cout << "String is: " <<
gfg;
}
};
// Driver code
int main()
{
GFG obj1;
obj1.gfg = "GeeksForGeeks is the best Technical Website";
obj1.print();
return 0;
}
C++
// C++ program to implement
// struct
#include
using namespace std;
struct Geeks
{
int a, b;
};
// Driver code
int main()
{
struct Geeks arr[10];
arr[0].a = 30;
arr[0].b = 40;
cout << arr[0].a << ", " <<
arr[0].b;
return 0;
}
C++
// C++ program to implement
// union
#include
using namespace std;
union gfg
{
int a, b;
};
// Driver code
int main()
{
union gfg g;
g.a = 5;
cout << "After changing a = 5:" <<
endl << "a = " << g.a <<
", b = " << g.b << endl;
g.b = 15;
cout << "After changing b = 15:" <<
endl << "a = " << g.a <<
", b = " << g.b << endl;
return 0;
}
C++
// C++ program to implement
// enum
#include
using namespace std;
enum season
{
Autmn, Spring, Winter, Summer
};
// Driver code
int main()
{
enum season month;
month = Summer;
cout << month;
return 0;
}
C++
// C++ program to implement
// arithmetic operators
#include
using namespace std;
// Driver code
int main()
{
int a = 5;
int b = 10;
cout << "Sum of a and b is" <<
" " << a + b << endl;
cout << "Difference of b and a is" <<
" " << b - a << endl;
cout << "Multiplication of a and b is" <<
" " << a * b << endl;
cout << "Division of b and a is" <<
" " << b / a << endl;
cout << "Modulo of b and a is" <<
" " << b % a << endl;
return 0;
}
C++
// C++ program to implement
// post-incrementer and
// post-decrementer
#include
using namespace std;
// Driver code
int main()
{
int a = 10;
int b;
int c;
b = a++;
cout << a << " " <<
b << endl;
c = a--;
cout << a << " " <<
c << endl;
return 0;
}
C++
// C++ program to implement
// pre-incrementer and
// pre-decrementer
#include
using namespace std;
// Driver code
int main()
{
int a = 10;
int b;
int c;
b = ++a;
cout << a << " " <<
b << endl;
c = --a;
cout << a << " " <<
c << endl;
return 0;
}
C++
// C++ program to implement
// relational operators
#include
using namespace std;
// Driver code
int main()
{
int a = 5;
int b = 10;
if (a == b)
{
cout << "a==b is not equal to true" <<
endl;
}
if (a != b)
{
cout << "a != b is true" <<
endl;
}
if (a > b)
{
cout << "a > b is not true" <<
endl;
}
if (a < b)
{
cout << "a < b is true" << endl;
}
if (a >= b)
{
cout << "a >= b is not true" <<
endl;
}
if (a <= b)
{
cout << "a <= b is true" <<
endl;
}
return 0;
}
C++
// C++ program to implement
// the logical operators
#include
using namespace std;
// Driver code
int main()
{
int a = 0;
int b = 1;
if (a && b)
{
cout << "a && b is false" <<
endl;
}
if (a || b)
{
cout << "a || b is true" <<
endl;
}
if (!a)
{
cout << "!a is true" <<
endl;
}
return 0;
}
C++
// C++ program to implement
// bitwise operators
#include
using namespace std;
// Driver code
int main()
{
// Binary representation
// of 5 is 0101
int a = 5;
// Binary representation
// of 6 is 0110
int b = 6;
cout << (a & b) << endl;
cout << (a | b) << endl;
cout << (a ^ b) << endl;
cout << (a << 1) << endl;
cout << (a >> 1) << endl;
return 0;
}
C++
// C++ program to implement
// assignment operator
#include
using namespace std;
// Driver code
int main()
{
// a is assigned value 5
int a = 5;
// a becomes 5
cout << a << endl;
// this is same as a=a+2
a += 2;
// a becomes 5+2 =7
cout << a << endl;
// this is same as a=a-2
a -= 2;
// a becomes 7-2 =5
cout << a << endl;
// this is same as a=a*2
a *= 2;
// a becomes 5*2 =10
cout << a << endl;
// this is same as a=a/2
a /= 2;
// a becomes 10/2 =5
cout << a << endl;
return 0;
}
C++
// C++ prorgam to implement
// miscellaneous operator
#include
using namespace std;
// Driver code
int main()
{
int a = 4;
// sizeof () returns the size
// of variable in bytes
cout << sizeof(a) << endl;
int x = 5;
int y = 8;
// ternary or conditional operator
int min = x < y ? x : y;
cout << "Minimum value from x and y is " <<
min << endl;
// casting from float to int
cout << int(4.350) << endl;
// comma operator is used for
int d = 2, b = 3, c = 4;
// multiple declarations
cout << d << " " << b << " " <<
c << " " << endl;
return 0;
}
C++
// C++ program to implement
// if-else
#include
using namespace std;
// Driver code
int main()
{
int age;
cin >> age;
if (age >= 18)
{
cout << "You can vote.";
}
else
{
cout << "Not eligible for voting.";
}
return 0;
}
C++
// C++ program to implement
// else if
#include
using namespace std;
// Driver code
int main()
{
int x, y;
cin >> x >> y;
if (x == y)
{
cout << "Both the numbers are equal";
}
else if (x > y)
{
cout << "X is greater than Y";
}
else
{
cout << "Y is greater than X";
}
return 0;
}
C++
// C++ program to implement
// nested if
#include
using namespace std;
// Driver code
int main()
{
int x, y;
cin >> x >> y;
if (x == y)
{
cout << "Both the numbers are equal";
}
else
{
if (x > y)
{
cout << "X is greater than Y";
}
else
{
cout << "Y is greater than X";
}
}
return 0;
}
C++
// C++ program to implement
// the switch statement
#include
using namespace std;
// Driver code
int main()
{
int n1, n2;
char op;
cout << "Enter 2 numbers: ";
cin >> n1 >> n2;
cout << "Enter operand: ";
cin >> op;
switch (op)
{
case '+':
cout << n1 + n2 << endl;
break;
case '-':
cout << n1 - n2 << endl;
break;
case '*':
cout << n1 * n2 << endl;
break;
case '/':
cout << n1 / n2 << endl;
break;
case '%':
cout << n1 % n2 << endl;
break;
default:
cout << "Operator not found!" <<
endl;
break;
}
return 0;
}
C++
// C++ program to implement
// for loop
#include
using namespace std;
// Driver code
int main()
{
for (int i = 1; i <= 5; i++)
{
cout << i << " ";
}
return 0;
}
C++
// C++ program to implement
// while loop
#include
using namespace std;
// Driver code
int main()
{
int i = 1;
while (i <= 5)
{
cout << i << " ";
i++;
}
return 0;
}
C++
// C++ program to implement
// do-while loop
#include
using namespace std;
// Driver code
int main()
{
int i = 1;
do {
cout << i << " ";
i++;
} while (i <= 5);
return 0;
}
C++
// C++ program to implement
// the continue statement
#include
using namespace std;
// Driver code
int main()
{
int i;
for (i = 1; i <= 20; i++)
{
if (i % 3 == 0)
{
continue;
}
cout << i << endl;
}
}
C++
// C++ program to implement
// the break statement
#include
using namespace std;
// Driver code
int main()
{
int i;
for (i = 1; i <= 20; i++)
{
if (i == 11)
{
break;
}
cout << i << endl;
}
}
Hello World!
C++代码的组件:
- 注释:两个斜杠(//)符号用于在程序中添加注释。它对程序的行为或结果没有任何影响。它用于描述您正在编写的程序。
- #include
: #include是预处理程序指令,用于在程序中包含文件。这里包含了iostream标准文件,该文件对于C++中的基本标准输入/输出库的声明是必需的。 - 使用名称空间std:标准C++库的所有元素都在名称空间中声明。在这里,我们使用std名称空间。
- int main():任何C++程序的执行都从main函数开始,因此有必要在程序中具有main函数。 ‘int’是此函数的返回值。 (稍后我们将更详细地研究功能)。
- {}:大括号用于指示任何函数的起点和终点。每个打开支架都应有一个相应的关闭支架。
- cout <<“ Hello World!\ n”;这是一个C++语句。 cout表示C++中的标准输出流。它在std名称空间内的iostream标准文件中声明。引号之间的文本将被打印在屏幕上。 \ n不会被打印,它用于添加换行符。 C++中的每个语句都以分号(;)结尾。
- 返回0; return表示函数结束。这里的函数是main,所以当我们点击return 0时,它将退出程序。我们返回0是因为我们提到主函数的返回类型为整数(int main)。零表示一切正常,一表示发生问题。
C++中的输入和输出
必须包括头文件iostream才能使用输入/输出(cin / cout)运算符。
标准输出(cout)
- 默认情况下,程序的标准输出指向屏幕。因此,使用cout运算符和“插入”运算符(фф),您可以在屏幕上打印一条消息。
- 要打印变量的内容,不使用双引号。
- <<运算符可以在单个语句中多次使用。
- 可以将变量和文本结合在一起:
- cout运算符不会在输出末尾放置换行符。所以,如果你想打印两句话,你将不得不使用新的行字符(\ n)的。
- 它可以使用ENDL操纵,而不是换行字符的。
以下是用于说明标准输出的C++程序:
C++
// C++ program to implement
// standard output
#include
using namespace std;
int main()
{
cout << "Geeks For Geeks";
return 0;
}
Geeks For Geeks
标准输入(cin)
- 在大多数情况下,标准输入设备是键盘。使用cin和>>运算符,可以从键盘读取输入。
- cin运算符将始终返回与cin一起使用的变量类型。因此,如果您请求一个整数,您将获得一个整数,依此类推。当程序的用户未返回您期望的类型时,这可能会导致错误。 (例如:你问了一个整数,你会得到字符串>)。
- cin运算符也是可链接的。在这种情况下,用户必须提供两个输入值,这些输入值由任何有效的空格分隔符(制表符,空格或换行符)分隔。
以下是用于说明标准输入的C++程序:
C++
// C++ program to implement
// standard input
#include
using namespace std;
int main()
{
int a;
cout << "Enter a number" << endl;
// User can input an integer
cin >> a;
cout << "User entered number " << a << endl;
}
Enter a number
User entered number 0
C++中的数据类型
数据类型是变量的声明。这确定了与变量相关联的数据的类型和大小,这些变量是必不可少的,因为不同的数据类型占用了不同的内存大小。
Data Type | Meaning | Size (in Bytes) |
---|---|---|
int | Integer | 4 |
float | Floating-point | 4 |
double | Double Floating-point | 8 |
char | Character | 1 |
wchar_t | Wide Character | 2 |
bool | Boolean | 1 |
void | Empty | 0 |
1. int
- 此数据类型用于存储整数。
- 它在内存中占用4个字节。
- 它可以存储从-2147483648到2147483647的值。
- 例如。年龄= 18
2.浮动并加倍
- 用于存储浮点数(小数和指数)
- 浮点数的大小为4个字节,双精度数的大小为8个字节。
- 浮点数用于存储最多7个十进制数字,而双精度码用于存储最多15个十进制数字。
- 例子:
- 浮动pi = 3.14。
- 两倍距离= 24E8 // 24 x 10 8
3.字符
- 此数据类型用于存储字符。
- 它在内存中占用1个字节。
- C++中的字符用单引号括起来”ASCII代码用于将字符存储在内存中。
- 示例:char ch =’a’
4.布尔
- 此数据类型只有2个值true和false。
- 它在内存中占用1个字节。
- True表示为1,false表示为0。
- 示例:布尔标志=假
C++类型修饰符
类型修饰符用于修改基本数据类型。
Data Type | Size (in Bytes) | Meaning |
---|---|---|
signed int | 4 | used for integers (equivalent to int) |
unsigned int | 4 | can only store positive integers |
short | 2 | used for small integers (range -32768 to 32767) |
long | at least 4 | used for large integers (equivalent to long int) |
long long int | 8 | used for very large integers (equivalent to long long int). |
unsigned long long(equivalent to unsigned long long int) | 8 | used for very large positive integers or 0 |
long double | 8 | used for large floating-point numbers |
signed char | 1 | used for characters (guaranteed range -127 to 127) |
unsigned char | 1 | used for characters (range 0 to 255) |
下面是实现数据类型的C++程序:
C++
// C++ program to implement
// data types
#include
using namespace std;
int main()
{
cout << "Size of bool is: " <<
sizeof(bool) <<
" bytes" << endl;
cout << "Size of char is: " <<
sizeof(char) <<
" bytes" << endl;
cout << "Size of int is: " <<
sizeof(int) <<
" bytes" << endl;
cout << "Size of short int is: " <<
sizeof(short int) <<
" bytes" << endl;
cout << "Size of long int is: " <<
sizeof(long int) <<
" bytes" << endl;
cout << "Size of signed long int is: " <<
sizeof(signed long int) <<
" bytes" << endl;
cout << "Size of unsigned long int is: " <<
sizeof(unsigned long int) <<
" bytes" << endl;
cout << "Size of float is: " <<
sizeof(float) <<
" bytes" << endl;
cout << "Size of double is: " <<
sizeof(double) <<
" bytes" << endl;
cout << "Size of wchar_t is: " <<
sizeof(wchar_t) << " bytes" << endl;
return 0;
}
Size of bool is: 1 bytes
Size of char is: 1 bytes
Size of int is: 4 bytes
Size of short int is: 2 bytes
Size of long int is: 8 bytes
Size of signed long int is: 8 bytes
Size of unsigned long int is: 8 bytes
Size of float is: 4 bytes
Size of double is: 8 bytes
Size of wchar_t is: 4 bytes
派生数据类型
这些是从基本(或内置)数据类型派生的数据类型。例如数组,指针,函数,引用。
下面是实现派生数据类型的C++程序:
C++
// C++ program to implement
// derived data types
#include
using namespace std;
// Function definition
int sum(int n1, int n2)
{
return n1 + n2;
}
int main()
{
// array declaration and
// initialization
int arr[5] = {2, 4, 6, 8, 10};
cout << "Array elements are : ";
for (int i = 0; i < 5; i++)
{
// printing array elements
cout << arr[i] << " ";
}
// pointers
int a = 10;
// Declared a pointer of
// type int
int* p;
// Pointer p points the address
// of a
p = &a;
cout << "\n" << "Value of a is " <<
a << endl;
// address of a will be printed
cout << "Value of p is " << p <<
endl;
// value of a will be printed
cout << "Value of *p is " << *p <<
endl;
// function calling from main
cout << "Sum is:" << sum(5, 2) <<
endl;
// reference
int x = 10;
int& ref = x;
// Value of x is now changed
// to 30
ref = 30;
cout << "x = " << x << endl;
// Value of x is now changed
// to 40
x = 40;
cout << "ref = " << ref << endl;
return 0;
}
Array elements are : 2 4 6 8 10
Value of a is 10
Value of p is 0x7ffd0ec3c084
Value of *p is 10
Sum is:7
x = 30
ref = 40
用户定义的数据类型
这些是用户自己定义的数据类型。
例如,类,结构,联合,枚举等。
下面是实现类用户定义数据类型的C++程序:
C++
// C++ program to implement
// user-defined data types
#include
using namespace std;
class GFG
{
public:
string gfg;
void print()
{
cout << "String is: " <<
gfg;
}
};
// Driver code
int main()
{
GFG obj1;
obj1.gfg = "GeeksForGeeks is the best Technical Website";
obj1.print();
return 0;
}
String is: GeeksForGeeks is the best Technical Website
下面是实现结构用户定义数据类型的C++程序:
C++
// C++ program to implement
// struct
#include
using namespace std;
struct Geeks
{
int a, b;
};
// Driver code
int main()
{
struct Geeks arr[10];
arr[0].a = 30;
arr[0].b = 40;
cout << arr[0].a << ", " <<
arr[0].b;
return 0;
}
30, 40
以下是用于实现联合用户定义的数据类型的C++程序:
C++
// C++ program to implement
// union
#include
using namespace std;
union gfg
{
int a, b;
};
// Driver code
int main()
{
union gfg g;
g.a = 5;
cout << "After changing a = 5:" <<
endl << "a = " << g.a <<
", b = " << g.b << endl;
g.b = 15;
cout << "After changing b = 15:" <<
endl << "a = " << g.a <<
", b = " << g.b << endl;
return 0;
}
After changing a = 5:
a = 5, b = 5
After changing b = 15:
a = 15, b = 15
下面是实现枚举数据类型的C++程序:
C++
// C++ program to implement
// enum
#include
using namespace std;
enum season
{
Autmn, Spring, Winter, Summer
};
// Driver code
int main()
{
enum season month;
month = Summer;
cout << month;
return 0;
}
3
C++中的运算符
运算符不过是告诉编译器执行某些特定操作的符号。运算符分为以下几种类型–
1.算术运算符
算术运算运算符对一个或两个操作数执行一些算术运算。对一个操作数进行运算的运算符称为一元算术运算符运算符,对两个操作数进行运算的运算符称为二进制算术运算运算符。
- +,-,*,/,%是二进制运算符。
- ++ —是一元运算运算符。
假设:A = 5,B = 10
Operator | Operation | Example |
---|---|---|
+ | Adds two operands | A+B = 15 |
– | Subtracts right operand from the left operand | B-A = 5 |
* | Multiplies two operands | A*B = 50 |
/ | Divides left operand by right operand | B/A = 2 |
% | Finds the remainder after integer division | B%A = 0 |
++ | Increment | A++ = 6 |
— | Decrement | A– = 4 |
下面是实现算术运算运算符的C++程序:
C++
// C++ program to implement
// arithmetic operators
#include
using namespace std;
// Driver code
int main()
{
int a = 5;
int b = 10;
cout << "Sum of a and b is" <<
" " << a + b << endl;
cout << "Difference of b and a is" <<
" " << b - a << endl;
cout << "Multiplication of a and b is" <<
" " << a * b << endl;
cout << "Division of b and a is" <<
" " << b / a << endl;
cout << "Modulo of b and a is" <<
" " << b % a << endl;
return 0;
}
Sum of a and b is 15
Difference of b and a is 5
Multiplication of a and b is 50
Division of b and a is 2
Modulo of b and a is 0
- Pre-incrementer :立即增加操作数的值。
- 后递增器:它临时存储操作数的当前值,只有在该语句完成后,操作数的值才会递增。
- 前置减数器:它立即减小操作数的值。
- 后减量器:它临时存储操作数的当前值,并且只有在该语句完成后,操作数的值才会递减。
下面是实现后递增和后递减的C++程序:
C++
// C++ program to implement
// post-incrementer and
// post-decrementer
#include
using namespace std;
// Driver code
int main()
{
int a = 10;
int b;
int c;
b = a++;
cout << a << " " <<
b << endl;
c = a--;
cout << a << " " <<
c << endl;
return 0;
}
11 10
10 11
以下是实现Pre-incrementer和Pre-decrementer的C++程序:
C++
// C++ program to implement
// pre-incrementer and
// pre-decrementer
#include
using namespace std;
// Driver code
int main()
{
int a = 10;
int b;
int c;
b = ++a;
cout << a << " " <<
b << endl;
c = --a;
cout << a << " " <<
c << endl;
return 0;
}
11 11
10 10
2.关系运算符
关系运算符定义2个实体之间的关系。它们给出布尔值作为结果,即true或false。
假设:A = 5,B = 10
Operator | Operation | Example |
---|---|---|
== | Gives true if two operands are equal | A==B is not true |
!= | Gives true if two operands are not equal | A!=B is true |
> | Gives true if the left operand is more than the right operand | A>B is not true |
< | Gives true if the left operand is less than the right operand | A |
>= | Gives true if the left operand is more than the right operand or equal to it | A>=B is not true |
<= | Gives true if the left operand is less than the right operand or equal to it | A<=B is true |
下面是实现关系运算符的C++程序:
C++
// C++ program to implement
// relational operators
#include
using namespace std;
// Driver code
int main()
{
int a = 5;
int b = 10;
if (a == b)
{
cout << "a==b is not equal to true" <<
endl;
}
if (a != b)
{
cout << "a != b is true" <<
endl;
}
if (a > b)
{
cout << "a > b is not true" <<
endl;
}
if (a < b)
{
cout << "a < b is true" << endl;
}
if (a >= b)
{
cout << "a >= b is not true" <<
endl;
}
if (a <= b)
{
cout << "a <= b is true" <<
endl;
}
return 0;
}
a != b is true
a < b is true
a <= b is true
3.逻辑运算符
逻辑运算符用于将多个表达式或条件连接在一起。我们有3个基本逻辑运算符。
假设:A = 0,B = 1
Operator | Operation | Example |
---|---|---|
&& | AND operator. Gives true if both operands are non-zero | (A && B) is false |
|| | OR operator. Gives true if at least one of the two operands are non-zero | (A || B) is true |
! | NOT operator. Reverse the logical state of the operand | !A is true |
下面是实现逻辑运算符的C++程序:
C++
// C++ program to implement
// the logical operators
#include
using namespace std;
// Driver code
int main()
{
int a = 0;
int b = 1;
if (a && b)
{
cout << "a && b is false" <<
endl;
}
if (a || b)
{
cout << "a || b is true" <<
endl;
}
if (!a)
{
cout << "!a is true" <<
endl;
}
return 0;
}
a || b is true
!a is true
例子:
- 如果需要检查数字是否可被2和3整除,则将使用AND运算符:(num%2 == 0)&& num(num%3 == 0)
- 如果此表达式给出真值,则意味着num可被2和3整除。(num%2 == 0)|| (num%3 == 0)
- 如果此表达式给出真值,则表示num可被2或3或两者整除。
4.按位运算符
按位运算符是对位进行运算并执行逐位运算的运算符。
假设:A = 5(0101)和B = 6(0110)
Operator | Operation | Example |
---|---|---|
& | Binary AND. Copies a bit to the result if it exists in both operands. |
0101 & 0110 ———- 0100 |
| | Binary OR. Copies a bit if it exists in either operand. |
0101 | 0110 ——— 0111 |
^ | Binary XOR. Copies the bit if it is set in one operand but not both. |
0101 ^ 0110 ———- 0011 |
~ | Binary One’s Complement. Flips the bit. | ~0101 => 1010 |
<< | Binary Left Shift. The left operand’s bits are moved left by the number of places specified by the right operand |
4 (0100) 4 << 1 = 1000 = 8 |
>> | Binary Right Shift Operator. The left operand’s bits are moved right by the number of places specified by the right operand. |
4 >> 1 = 0010 = 2 |
如果将移位运算符应用于数字N,
- N << a将得出结果N * 2 ^ a
- N >> a将得出结果N / 2 ^ a
下面是实现按位运算运算符的C++程序:
C++
// C++ program to implement
// bitwise operators
#include
using namespace std;
// Driver code
int main()
{
// Binary representation
// of 5 is 0101
int a = 5;
// Binary representation
// of 6 is 0110
int b = 6;
cout << (a & b) << endl;
cout << (a | b) << endl;
cout << (a ^ b) << endl;
cout << (a << 1) << endl;
cout << (a >> 1) << endl;
return 0;
}
4
7
3
10
2
5.赋值运算符
Operator | Operation | Example |
---|---|---|
= | Assigns the value of right operand to left operand. | A=B will put the value of B in A |
+= | Adds the right operand to the left operand and assigns the result of the left operand. | A+=B means A=A+B |
-= | Subtracts the right operand from the left operand and assigns the result to the left operand. | A-=B means A=A-B |
*= | Multiplies the right operand with the left operand and assigns the result to the left operand. | A*=B means A=A*B |
/= | Divides left operand with the right operand and assign the result to the left operand. | A/=B means A=A/B |
下面是实现赋值运算符的C++程序:
C++
// C++ program to implement
// assignment operator
#include
using namespace std;
// Driver code
int main()
{
// a is assigned value 5
int a = 5;
// a becomes 5
cout << a << endl;
// this is same as a=a+2
a += 2;
// a becomes 5+2 =7
cout << a << endl;
// this is same as a=a-2
a -= 2;
// a becomes 7-2 =5
cout << a << endl;
// this is same as a=a*2
a *= 2;
// a becomes 5*2 =10
cout << a << endl;
// this is same as a=a/2
a /= 2;
// a becomes 10/2 =5
cout << a << endl;
return 0;
}
5
7
5
10
5
6.杂项运算符
Operator | Operation | Example |
---|---|---|
sizeof() | Returns the size of the variable. | If a is an integer then sizeof(a) will return 4. |
Condition?X:Y | Conditional operator. If the condition is true, then returns the value of X or else the value of Y. | A+=B means A=A+B |
Cast | The casting operator convert one data type to another | int(4.350) would return 4. |
Comma(,) | Comma operator causes a sequence of operations to be performed. The value of the entire comma expression is the value of the last expression of the comma-separated list. |
下面是实现杂类运算符的C++程序:
C++
// C++ prorgam to implement
// miscellaneous operator
#include
using namespace std;
// Driver code
int main()
{
int a = 4;
// sizeof () returns the size
// of variable in bytes
cout << sizeof(a) << endl;
int x = 5;
int y = 8;
// ternary or conditional operator
int min = x < y ? x : y;
cout << "Minimum value from x and y is " <<
min << endl;
// casting from float to int
cout << int(4.350) << endl;
// comma operator is used for
int d = 2, b = 3, c = 4;
// multiple declarations
cout << d << " " << b << " " <<
c << " " << endl;
return 0;
}
4
Minimum value from x and y is 5
4
2 3 4
运算符的优先级
Category | Operator | Associativity |
---|---|---|
Postfix | () [] -> . ++ — | Left to right |
Unary | + – ! ~ ++ __ (type) * & sizeof | Right to left |
Multiplicative | * / % | Left to right |
Additive | + – | Left to right |
Shift | << >> | Left to right |
Relational | < <= > >= | Left to right |
Equality | == != | Left to right |
Bitwise AND | & | Left to right |
Bitwise XOR | ^ | Left to right |
Bitwise OR | | | Left to right |
Logical AND | && | Left to right |
Logical OR | || | Left to right |
Conditional | ?: | Right to left |
Assignment | = += -= /= %= >>= <<= &= ^= |= | Right to left |
Comma | , | Left to right |
做决定
1.如果/否则
如果if块中指定的条件为true,则if块用于指定要执行的代码,否则执行else块。下面是实现if-else的C++程序:
C++
// C++ program to implement
// if-else
#include
using namespace std;
// Driver code
int main()
{
int age;
cin >> age;
if (age >= 18)
{
cout << "You can vote.";
}
else
{
cout << "Not eligible for voting.";
}
return 0;
}
Not eligible for voting.
2.否则,如果
为了指定多个if条件,我们首先使用if,然后连续的语句使用else if。下面是要实现else的C++程序:
C++
// C++ program to implement
// else if
#include
using namespace std;
// Driver code
int main()
{
int x, y;
cin >> x >> y;
if (x == y)
{
cout << "Both the numbers are equal";
}
else if (x > y)
{
cout << "X is greater than Y";
}
else
{
cout << "Y is greater than X";
}
return 0;
}
Y is greater than X
3.如果嵌套
为了在条件内指定条件,我们使用嵌套的ifs。下面是实现嵌套的C++程序:
C++
// C++ program to implement
// nested if
#include
using namespace std;
// Driver code
int main()
{
int x, y;
cin >> x >> y;
if (x == y)
{
cout << "Both the numbers are equal";
}
else
{
if (x > y)
{
cout << "X is greater than Y";
}
else
{
cout << "Y is greater than X";
}
}
return 0;
}
Y is greater than X
4.切换语句
Switch case语句代替了将变量与多个值进行比较的long if语句。找到匹配项后,它将执行该值大小写的相应代码。
句法:
switch (n)
{
case 1: // code to be executed if n == 1;
break;
case 2: // code to be executed if n == 2;
break;
default: // code to be executed if n doesn't match any of the above cases
}
- 开关中的变量应具有恒定值。
- break语句是可选的。它终止switch语句,并将控制移至切换后的下一行。
- 如果未添加break语句,则该开关不会终止,它将继续到该开关之后的下一行。
- 每个案例值都应该是唯一的。
- 默认情况是可选的。但是很重要,因为在没有大小写值匹配的情况下可以执行该命令。
使用switch语句的基本计算器:
C++
// C++ program to implement
// the switch statement
#include
using namespace std;
// Driver code
int main()
{
int n1, n2;
char op;
cout << "Enter 2 numbers: ";
cin >> n1 >> n2;
cout << "Enter operand: ";
cin >> op;
switch (op)
{
case '+':
cout << n1 + n2 << endl;
break;
case '-':
cout << n1 - n2 << endl;
break;
case '*':
cout << n1 * n2 << endl;
break;
case '/':
cout << n1 / n2 << endl;
break;
case '%':
cout << n1 % n2 << endl;
break;
default:
cout << "Operator not found!" <<
endl;
break;
}
return 0;
}
Enter 2 numbers: Enter operand: Operator not found!
C++中的循环
循环用于重复执行语句块,直到满足特定条件为止。循环由初始化语句,测试条件和增量语句组成。
1. for循环
for循环的语法是
for (initialization; condition; update)
{
// body of-loop
}
下面是实现for循环的C++程序:
C++
// C++ program to implement
// for loop
#include
using namespace std;
// Driver code
int main()
{
for (int i = 1; i <= 5; i++)
{
cout << i << " ";
}
return 0;
}
1 2 3 4 5
解释:
for循环由值1初始化,测试条件为i <= 5,即执行循环直到i的值保持小于或等于5。在每次迭代中,通过执行以下操作将i的值增加1我++。
2. while循环
while循环的语法是
while (condition)
{
// body of the loop
}
下面是实现while循环的C++程序:
C++
// C++ program to implement
// while loop
#include
using namespace std;
// Driver code
int main()
{
int i = 1;
while (i <= 5)
{
cout << i << " ";
i++;
}
return 0;
}
1 2 3 4 5
解释:
while循环由值1初始化,测试条件为i <= 5,即执行循环直到i的值保持小于或等于5。在每次迭代中,通过执行以下操作将i的值增加1我++。
3.做͙while循环
while循环的语法是
do {
// body of loop;
}
while (condition);
下面是实现do-while循环的C++程序:
C++
// C++ program to implement
// do-while loop
#include
using namespace std;
// Driver code
int main()
{
int i = 1;
do {
cout << i << " ";
i++;
} while (i <= 5);
return 0;
}
1 2 3 4 5
解释:
do-while循环变量由值1初始化,在每次迭代中,i的值通过执行i ++递增1,测试条件为i <= 5,即执行循环直到i的值保持小于或等于5。由于仅在循环已经运行一次后才检查测试条件,所以do-while循环至少运行一次。
循环跳
循环跳转用于控制循环流。有两个用于实现跳转循环的语句-Continue和Break。当需要满足某些指定条件时需要更改循环流时,将使用这些语句。
1.继续
continue语句用于跳到该循环的下一个迭代。这意味着它将停止循环的一次迭代。该循环中continue语句之后出现的所有语句都不会执行。
以下是实现Continue语句的C++程序:
C++
// C++ program to implement
// the continue statement
#include
using namespace std;
// Driver code
int main()
{
int i;
for (i = 1; i <= 20; i++)
{
if (i % 3 == 0)
{
continue;
}
cout << i << endl;
}
}
1
2
4
5
7
8
10
11
13
14
16
17
19
20
解释:
在此for循环中,无论何时我是一个可被3整除的数字,都将不打印该数字,因为由于continue语句,该循环将跳至下一个迭代。因此,将打印除可被3整除的所有数字。
2.休息
break语句用于终止当前循环。一旦在循环中遇到break语句,该循环的所有其他迭代都将停止,并且控制将在循环结束后移至第一个语句。
下面是实现break语句的C++程序:
C++
// C++ program to implement
// the break statement
#include
using namespace std;
// Driver code
int main()
{
int i;
for (i = 1; i <= 20; i++)
{
if (i == 11)
{
break;
}
cout << i << endl;
}
}
1
2
3
4
5
6
7
8
9
10
解释:
在此循环中,当i等于11时,for循环由于break语句而终止,因此,程序将仅打印1到10之间的数字。