#include
#define P 3.1415927
#define toFeet(x) x/12.0
#define toMiles(x) x/5280.0
int main() {
double diameter; // 車輪直徑 (英寸)
int revolutions; // 轉數
double time; // 時間 (秒)
double s; // 距離 (英里)
int count = 1; // 行程計數器
// 循環讀取,直到 revolutions 為 0
while (scanf("%lf %d %lf", &diameter, &revolutions, &time), revolutions) {
time /= 3600; // 秒 -> 小時
diameter /= 63360; // 英寸 -> 英里 (63360 = 5280*12)
s = diameter * P * revolutions; // 距離 = 周長 * 轉數
printf("Trip #%d: %.2lf %.2lf\n", count++, s, s/time); // 距離, 速度
}
return 0;
}
import java.util.Scanner;
public class TripCalculator {
private static final double PI = 3.1415927;
private static final double INCHES_PER_MILE = 63360.0; // 5280 * 12
private static final double SECONDS_PER_HOUR = 3600.0;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int tripCount = 1;
System.out.println("請輸入 直徑(英寸) 轉數 時間(秒),輸入 0 結束:");
while (scanner.hasNext()) {
double diameter = scanner.nextDouble();
int revolutions = scanner.nextInt();
double timeSec = scanner.nextDouble();
// 終止條件:轉數為 0
if (revolutions == 0) break;
// 單位換算
double timeHours = timeSec / SECONDS_PER_HOUR;
double diameterMiles = diameter / INCHES_PER_MILE;
// 計算距離 (英里) 和速度 (英里/小時)
double distance = diameterMiles * PI * revolutions;
double speed = distance / timeHours;
// 格式化輸出:保留兩位小數
System.out.printf("Trip #%d: %.2f %.2f%n", tripCount++, distance, speed);
}
scanner.close();
}
// 輔助方法 (對應 C 宏)
public static double toFeet(double inches) { return inches / 12.0; }
public static double toMiles(double feet) { return feet / 5280.0; }
}
| 特性 | C 原版 | Java 版 | 說明 |
|---|---|---|---|
| 輸入掃描 | `scanf("%lf %d %lf", ...)` | `Scanner.nextDouble()/nextInt()` | Java 類型安全、異常處理 |
| 循環終止 | 逗號表達式 `scanf(...), revolutions` | 獨立 `if (revolutions == 0) break;` | Java 無逗號表達式,邏輯更清晰 |
| 常量定義 | `#define` 宏 | `static final` 常量 | Java 有類型檢查、作用域 |
| 格式化輸出 | `printf("%.2lf", ...)` | `System.out.printf("%.2f", ...)` | 語法幾乎相同,`%lf` → `%f` |
| 主方法 | `int main()` 返回 0 | `void main(String[] args)` 無返回 | JVM 管理進程退出碼 |
| 資源管理 | 無需關閉 stdin | `scanner.close()` 釋放資源 | 良好習慣 |
輸入: 26 1000 3600 27 2000 7200 0 0 0 輸出: Trip #1: 1.29 1.29 Trip #2: 2.68 1.34
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) { // try-with-resources 自動關閉
int tripCount = 1;
while (true) {
if (!scanner.hasNextDouble()) break; // EOF 或非數字
double diameter = scanner.nextDouble();
if (!scanner.hasNextInt()) break;
int revolutions = scanner.nextInt();
if (!scanner.hasNextDouble()) break;
double timeSec = scanner.nextDouble();
if (revolutions == 0) break;
double distance = (diameter / INCHES_PER_MILE) * PI * revolutions;
double speed = distance / (timeSec / SECONDS_PER_HOUR);
System.out.printf("Trip #%d: %.2f %.2f%n", tripCount++, distance, speed);
}
} // scanner 自動 close
}
C 到 Java 移植核心:**`scanf` → `Scanner`、宏 → `final` 常量、逗號表達式 → 獨立判斷、`printf` → `printf` 格式微調、主函數簽名適配**。保持業務邏輯 (單位換算、循環終止條件) 完全一致。Java 版更健壯、類型安全、資源管理規範。