輸入一系列正整數(每行一個),輸入 0 結束。對每個正整數輸出其平方根(一行一個結果)。
#include <math.h>
#include <stdio.h>
int main() {
int x;
while (1) {
scanf("%d", &x);
if (x == 0) break;
// sqrt 接受 double,轉換避免警告;輸出用 %f 或 %lf
printf("%lf\n", sqrt((double)x));
}
return 0;
}
#include <math.h>:引入 sqrt 函數聲明。(double)x:整數隱式轉換為 double,也可寫 sqrt(x) 依賴隱式轉換,但顯式轉型更規範。%lf:printf 中 %f 和 %lf 均可輸出 double(C99 起),scanf 必須用 %lf 讀 double。while(1) + break 簡潔處理「輸入 0 終止」。scanf 返回值判斷是否成功讀取整數。int 範圍內 sqrt 精度足夠;超大整數需高精度庫。%lf 默認 6 位小數;如需定製用 %.2f 等。