C++ 增加和减少运算符
什么是C ++递增运算符的定义
C ++中的递增运算符是一个一元运算符。递增运算符由符号(++)表示。递增运算符将变量中记录的值加一。此运算符仅适用于数字。
C++递增运算符分为两种类型
- 前递增
- 后递增
1. 后递增运算符(a++)
后缀运算符表示值应先使用,然后递增。这意味着该值首先被用于操作,然后递增一个。
C++代码:
#include
using namespace std;
int main()
{
int p = 7;
cout << " The value before employing the post increment operator is"
": "
<< p << endl;
int temp = p++;
cout << " The value held by temp is: " << temp
<< endl;
cout << " The result of applying the post increment operator is: "
<< p << endl;
return 0;
}
输出
The value before employing the post increment operator is: 7
The value held by temp is: 7
The result of applying the post increment operator is: 8
2. pre-increment运算符(++a)
后缀运算符指定在使用之前对值进行递增。这意味着该值在操作中增加了一,并且然后被变量使用。
C++代码:
#include
using namespace std;
int main()
{
int p = 7;
cout << " The value before employing the pre increment operator is"
": "
<< p << endl;
int temp = ++p;
cout << " The value held by temp is: " << temp
<< endl;
cout << " The result of applying the pre increment operator is: "
<< p << endl;
return 0;
}
输出
The value before employing the pre increment operator is: 7
The value held by temp is: 8
The result of applying the pre increment operator is: 8
什么是C++减法运算符
C++中的减法运算符是一元运算符。减法运算符用符号(-)表示。减法运算符将变量的值减一。该运算符仅适用于数字。
C++减法运算符分为两种类型
- 后减法运算符
- 前减法运算符
1. 后减法运算符 (a–)
后缀运算符表示先使用值,然后再减少。这意味着值先用于操作,然后减少一。
C++ 代码:
#include
using namespace std;
int main()
{
int p = 7;
cout << " The value before employing the post decrement operator is"
": "
<< p << endl;
int temp = p--;
cout << " The value held by temp is: " << temp
<< endl;
cout << " The result of applying the post decrement operator is: "
<< p << endl;
return 0;
}
输出
The value before employing the post decrement operator is: 7
The value held by temp is: 7
The result of applying the post decrement operator is: 6
2. 前置递减运算符 (–a)
后置递减运算符指示在使用之前应该减小数值。这意味着数值在操作时减一,并且变量会使用这个减小后的数值。
C++代码:
#include
using namespace std;
int main()
{
int p = 7;
cout << " The value before employing the pre decrement operator is"
": "
<< p << endl;
int temp = --p;
cout << " The value held by temp is: " << temp
<< endl;
cout << " The result of applying the pre decrement operator is: "
<< p << endl;
return 0;
}
输出
The value before employing the pre decrement operator is: 7
The value held by temp is: 6
The result of applying the pre decrement operator is: 6