//p06.c --- 使用 fgets( ) 先讀入整列字串 //@CopyLeft by tsaiwn@csie.nctu.edu.tw //這是把 p05.c 略作修改: 把讀取實數的工作踢出去給一個小弟(函數) #include #include #include double x; // (注意 1) 變數 variable; // C++ 式的註解 comment double getReal( ); // 會回傳 a double 的小弟函數 int main( ) { // 大多數 main program 都這樣開頭 double ans; printf("Give me x: "); x = getReal( ); // 請小弟(function)幫忙讀入一個兩倍準的實數 ans = sqrt(x); printf(" sqrt 根號 %f =%f\n ", x, ans ); printf("Bye bye!\n"); printf(" Hit ENTER key..."); // prompt the user getchar( ); // 等 User 敲下 ENTER 鍵 return 0; // 告知作業系統(OS)表示我們這主程式正常結束 }// main( double getReal( ) { double ans; // 這是我自己的變數 (Local auto variable) static char buf[99]; fgets(buf, sizeof(buf), stdin); // stdin 就是鍵盤, 要記得含入 ans = atof(buf); // atof() 是宣告在 return ans; }// getReal( /*************** Running script D:\test> D:\test> path C:\Dev-Cpp\bin;%path% D:\test> gcc p06.c D:\test> a.exe Give me x: abcde sqrt 根號 0.000000 =0.000000 Bye bye! D:\test> a Give me x: 9 sqrt 根號 9.000000 =3.000000 Bye bye! D:\test> a Give me x: 2 sqrt 根號 2.000000 =1.414214 Bye bye! D:\test> path C:\TC\BIN;%path% D:\test> tcc p06.c Turbo C++ Version 3.00 Copyright (c) 1992 Borland International p06.c: Turbo Link Version 5.0 Copyright (c) 1992 Borland International Available memory 4106928 D:\test> p06 Give me x: 2 sqrt 根號 2.000000 =1.414214 Bye bye! ********************************/