c ++ << 输出运算符
Program 1:
程序1:
#include <iostream>
using namespace std;
int main()
{
int A = 5, B = 40, C = 0;
C = (A << 2) + (B >> 3);
cout << C;
return 0;
}
Output:
输出:
25
Explanation:
说明:
In the above code, we use the left shift and right shift operators. Now we will understand the easy way how it works in the evaluation of an expression in C++?
在上面的代码中,我们使用左移和右移运算符。 现在我们将了解在C ++中对表达式求值的简单方法。
We can understand the left shift operator using below statement:
我们可以使用以下语句来了解左移运算符:
= 10 << 3
= 10 * pow(2,3)
= 10 * 8
= 80
We can understand the right shift operator using below statement:
我们可以使用以下语句了解正确的移位运算符:
= 10 >> 3
= 10 / pow(2,3)
= 10 / 8
= 1
Now we come to the evaluation of expression mentioned in above code.
现在我们来评估上面代码中提到的表达式。
C = (A<<2) + (B>>3)
= (5<<2) + (40>>3)
= 5 * pow(2,2) + 40 /pow(2,3)
= 5 * 4 + 40 / 8
= 20 + 5
= 25
Then the final value of C is 25.
那么C的最终值为25。
Program 2:
程式2:
#include <iostream>
using namespace std;
int main()
{
int C;
C = (80 >> 5) ? (120 << 3) ? (10 > (5 + 5)) ? 1 : 5 : 10 : 20;
cout << C;
return 0;
}
Output:
输出:
5
Explanation:
说明:
In the above program, we used a nested ternary operator and shift operators, now we evaluate the expression.
在上面的程序中,我们使用了嵌套三元运算符和shift运算符 ,现在我们对表达式进行了计算。
C = (80>>5)?(120<<3)?(10>(5+5))?1:5:10:20
= (80/pow(2,5)) ? (120*pow(2,3))?(10>10)?1:5:10:20
= (80/32)?(120*8)?(10>10)?1:5:10:20
= (2) ? (960)?(10>10)?1:5:10:20
2 it means the condition is true then
2这意味着条件为真
960 that is again true
960又是真的
Then 10>10 that is false then 5 will be returned.
然后10> 10为假,则返回5。
Then the final value of C is 5.
那么C的最终值为5。
Program 3:
程式3:
#include <iostream>
using namespace std;
int main()
{
int A = 10, B = 20, C = 0;
C = A++ + ++B * 10 + B++;
cout << A << "," << B << "," << C;
return 0;
}
Output:
输出:
11, 22, 241
Explanation:
说明:
In the above program, we took 3 local variables A, B, and C that contain the values 10, 20, and 0 respectively. Here we used an expression that contains pre, post-increment, and arithmetic operators, as we know that pre-increment increases the value of the variable before evaluation of the expression, and post-increment increases the value of the variable after evaluation.
在上面的程序中,我们采用了3个局部变量A , B和C ,它们分别包含值10、20和0。 在这里,我们使用了一个包含pre,post后递增和算术运算符的表达式,因为我们知道pre-increment在评估表达式之前会增加变量的值,而post-increment在评估之后会增加变量的值。
Values of A and B before the evaluation of expression due to pre-increment are:
由于预先增加,在评估表达之前的A和B值为:
A = 10, B = 21
Now we evaluate the expression:
现在我们评估表达式:
C = 10 + 21 * 10 + 21
= 10 +210 +21
= 241
Then the value of C is 241. And values of A and B after evaluation of express due to post-increment operator are:
那么C的值为241。由于后增量运算符而对express进行评估后, A和B的值为:
A = 11, B = 22
Then the final values are: A =11, B= 22, C=241
那么最终值为: A = 11,B = 22,C = 241
Note: Compiler dependency may be there.
注意:可能存在编译器依赖性。
Recommended posts
推荐的帖子
翻译自: https://www.includehelp.com/cpp-tutorial/operators-find-output-programs-set-2.aspx
c ++ << 输出运算符