Operators and Basic I/O Operatio

2016-12-05  本文已影响11人  某右衛門

LT3 Basic Syntax - Operators and Basic I/Operations

Operators & Punctuators

An operator specifies an operation on values: + - * / % ++ -- >> <<

Increment & Decrement Operators
  1. Post-Increment & Post-Decrement Operators: c++ & c--
  1. Pre-Increment & Pre-Decrement Operators: ++c & --c
Predecence & Associativity of Operators

An expression may have multiple operators.

  1. Predecence: order for different operators: + - are behind * /
  2. 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)
  1. ::
  2. . -> [], LTR
  3. (force to define predecence) post++ post--, LTR
  4. Prefix + -, ++pre --pre, RTL
  5. * / %, LTR
  6. + -, LTR
  7. =, +=, -=, *=, /=, 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

The Output Operator: <<

Manipulators: #include<iomanip>

  1. Weights (right-aligning)

    1. cout.width(5); // no need of <iomanip>
    2. 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
  2. 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
    1. fixed: fixed digits after the decimal point
      `cout<<setprecision(2)<<fixed<<12.18642; // 12.19
    2. 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
  3. Other Manipulators

    1. setfill('x'): change the blank filling into other chars e.g.: '*'
    2. Radix: << oct / dec / hex <<
    3. Alignment: << setiosflags(ios::left) << setw(20); change the alignment of width from right to left
上一篇 下一篇

猜你喜欢

热点阅读