next up previous contents
Next: 錯誤處理 Up: 其他 Previous: 記憶體管理   Contents

型態轉變

  1. cast 運算子宣告
    (type_name) expression
    
  2. 使用範例:sum 前有 cast 運算子 (double),sum 會先轉成 double,再進行除法運算。
    #include <stdio.h>
    
    main()
    {
       int sum = 17, count = 5;
       double mean;
    
       mean = (double) sum / count;
       printf("Value of mean : %f\n", mean );
    
    }
    
  3. 整數升級:型態大小小於 int 或 unsigned int,例如 char 與整數進行運算時直接升級成整數。
    #include <stdio.h>
    
    main()
    {
       int  i = 17;
       char c = 'c'; /* ascii value is 99 */
       int sum;
    
       sum = i + c;
       printf("Value of sum : %d\n", sum );
    
    }
    
  4. 算術轉換:算術運算時若包含不同型態的變數,編譯器自動升級下層變數,變數層級如下:

    \begin{tikzpicture}[node distance=1.5cm,auto]\setlength \baselineskip{1ex}
\node [] (ld) {long double};
\node [below of=ld] (double) {double};
\node [below of=double] (float) {float};
\node [below of=float] (unll) {unsigned long long};
\node [below of=unll] (ll) {long long};
\node [below of=ll] (unl) {unsigned long};
\node [below of=unl] (long) {long};
\node [below of=long] (unint) {unsigned int};
\node [below of=unint] (int) {int};
\path [line] (int) --(unint);
\path [line] (unint) -- (long);
\path [line] (long) -- (unl);
\path [line] (unl) -- (ll);
\path [line] (ll) -- (unll);
\path [line] (unll) -- (float);
\path [line] (float) -- (double);
\path [line] (double) -- (ld);
\end{tikzpicture}

  5. 使用範例:
    #include <stdio.h>
    
    main()
    {
       int  i = 17;
       char c = 'c'; /* ascii value is 99 */
       float sum;
    
       sum = i + c;
       printf("Value of sum : %f\n", sum );
    
    }
    



2015-01-16