
%g (或 %G) 是 printf 家族中智能選擇定點或科學記數法的格式符。它根據數值大小自動決定輸出風格:
%e/%E)%f)
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
void main() {
printf("Displaying 0.1234 yields %g\n", 0.1234);
printf("Displaying 0.00001234 yields %g\n", 0.00001234);
system("pause");
}
Displaying 0.1234 yields 0.1234 Displaying 0.00001234 yields 1.234e-05
0.1234:指數為 0 (10^0),在 [-4, 6) 範圍內 (預設精度 6) → 定點輸出 0.12340.00001234 = 1.234e-5:指數 -5 < -4 → 科學記數法輸出 1.234e-05| 數值範圍 | 輸出風格 | 示例 |
|---|---|---|
| |x| ≥ 10^精度 | 科學記數法 | 1234567 → 1.23457e+06 (精度 6) |
| |x| < 10^-4 | 科學記數法 | 0.00001234 → 1.234e-05 |
| 10^-4 ≤ |x| < 10^精度 | 定點記數法 | 0.1234 → 0.1234 |
%.3g 表示有效數字為 3 位 (非小數位)。
printf("%.3g\n", 12345); // 1.23e+04
printf("%.3g\n", 1.2345); // 1.23
printf("%.3g\n", 0.0012345); // 0.00123
1.2000 → 1.2%G 使用大寫 E:1.234E-05