next up previous contents
Next: 實機練習題 Up: 資料型態 Previous: 反斜線跳脫   Contents

資料型態轉換

  1. 資料型態轉換語法:
    (data type) variable_name
    
  2. 算術轉換:算術運算時若包含不同型態的變數,編譯器自動升級下層變數,變數層級如下:
    \begin{tikzpicture}[node distance=1cm,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}

  3. 範例:浮點數轉整數
    [dywang@dyw219 zzz]$ vim typetran1.c
    [dywang@dyw219 zzz]$ cat typetran1.c
    #include <stdio.h>
    
    main() {
    	int n1, n2;
    	float f1=3.14159, f2=5.987;
    	n1 = (int) f1;
    	n2 = (int) f2;
    	printf("f1 = %f, n1 = %d\n", f1, n1);
    	printf("f2 = %f, n2 = %d\n", f2, n2);
    }
    
  4. 編譯成功
    [dywang@dyw219 zzz]$ gcc -o typetran1 typetran1.c
    
  5. 執行結果:浮點數轉整數,小數點部分直接捨去,不是四捨五入。
    [dywang@dyw219 zzz]$ ./typetran1 
    f1 = 3.141590, n1 = 3
    f2 = 5.987000, n2 = 5
    



De-Yu Wang 2019-08-14