//p03.c --- Sample program to find Square Root of real numbers // @CopyLeft by tsaiwn@csie.nctu.edu.tw #include #include #include double x; // (注意 1) 變數 variable; // C++ 式的註解 comment double getDBL(void); // (注意 2)寫成 function 比較有彈性:-) int main( ) { // 大多數 main program 都這樣開頭 while(38==38) { // (注意 3) 可以改用別的方法; for(;;) { printf("Give me x: "); x = getDBL( ); // 寫成函數 (function; 函式) 是個很好的習慣 if( x < 0 ) break; // (注意 3) 可以改用別的方法 printf(" sqrt 根號 %f =%f\n ", x, sqrt(x) ); // (注意 4) 可以問 user 要不要繼續? } // while printf("Bye bye!\nHit ENTER key..."); // 告訴 User :-) getchar( ); // 等 User 按下 ENTER 鍵 return 0; // 告知作業系統(OS)表示我們這主程式正常結束 } // main( double getDBL( ) { // 以後要改輸入的方法只要改這 function 就可 :-) static char buf[99]; // a string buffer for input; why "static" ? double ans; fgets(buf, sizeof(buf), stdin); // stdin 就是鍵盤, 要記得含入 ans = atof(buf); // 從字串中讀出兩倍準的實數 (double) return ans; } // getDBL( /************** Running Script D:\test> D:\test> path C:\Dev-Cpp\bin;%path% D:\test> gcc p03sqrt.c D:\test> a.exe Give me x: 2 sqrt 根號 2.000000 =1.414214 Give me x: 3 sqrt 根號 3.000000 =1.732051 Give me x: 100 sqrt 根號 100.000000 =10.000000 Give me x: 9 sqrt 根號 9.000000 =3.000000 Give me x: 625 sqrt 根號 625.000000 =25.000000 Give me x: 179 sqrt 根號 179.000000 =13.379088 Give me x: -1 Bye bye! Hit ENTER key... D:\test> **********************************************/