LT3 Basic Syntax - Operators and Basic I/Operations
Operators & Punctuators
An operator specifies an operation on values: + - * / % ++ -- >> <<
- The values are called Operands of the operator
Increment & Decrement Operators
- Post-Increment & Post-Decrement Operators: c++ & c--
- Return the origin value, then operate
- Pre-Increment & Pre-Decrement Operators: ++c & --c
- Operate first, then return the manipulated value
Predecence & Associativity of Operators
An expression may have multiple operators.
- Its precise meaning depends on the predecence and associativity of the operators
- Predecence: order for different operators:
+ -
are behind* /
- Associativity: order for operators with same precedence:
- an expression like x R y R z should be evaluated L-R or R-L
Operator Predecence (Hi to Lo)
::
-
. -> []
, LTR -
(force to define predecence) post++ post--
, LTR -
Prefix + -, ++pre --pre
, RTL -
* / %
, LTR -
+ -
, LTR -
=, +=, -=, *=, /=
, RTL: Evaluate the right value, and then pass to left
An Important Notice For Postfix Increment & Decrement
Although the predecence of c++ and ++c is high,
The evaluation immediately returns the value of c
However the increment / decrement operation, will be executed after all else is done
Assignment Operator
variable = expression;
the return value is the value of the RHS expression
a = (b = 1) + (c = 2) // a = 1 + 2
Efficient Assignment Operators:
+=, -=, *=, /=, %=
Basic IO
- cin >> keyboard
- cout << screen
The Output Operator: <<
- Predefined for all standard C++ data types
- send bytes to the output device
- predfined manipulators can be used for formatting
Manipulators: #include<iomanip>
-
Weights (right-aligning)
cout.width(5); // no need of <iomanip>
-
cout<<setw(5)<<"Hi"; // output "___Hi", right alighed
- Leading fillings are added before any value fewer than the width
- Effective only for once, have to call every times
-
Precision:
cout<<setprecesion()
Floating-point type's precision is 6, by default
- Permanent Effect
- can use
fixed
/scientific
to set the number of digits AFTER the DECIMAL POINT
-
fixed
: fixed digits after the decimal point
`cout<<setprecision(2)<<fixed<<12.18642; // 12.19 -
scientific
: Always use the scientific notation, fix the digits after decimal (1-9).(0-9){precision}
cout<<setprecision(2)<<scientific<<12334.123; // 1.23e+04
-
Other Manipulators
-
setfill('x')
: change the blank filling into other chars e.g.: '*' - Radix:
<< oct / dec / hex <<
- Alignment:
<< setiosflags(ios::left) << setw(20)
; change the alignment of width from right to left
-
网友评论