日期:2025年2月15日
ZeroJudge 題目連結:e948. 基礎代謝率 (BMR Calculation)
解題想法
這題考輸出格式,要輸出小數點後 2 位,如果是用 C++ 可以用 printf 會比較方便。
Python 程式碼
使用時間約為 18 ms,記憶體約為 3.3 MB,通過測試。
n = int(input()) # 人數
for _ in range(n): # 執行 n 次
g, a, h, w = map(int, input().split()) # 性別、年齡、身高、體重
if g == 1: # 男
print(f"{13.7*w + 5.0*h - 6.8*a + 66:.2f}")
else: # 女
print(f"{9.6*w + 1.8*h - 4.7*a + 655:.2f}")
C++ 程式碼
使用 iomanip 函式庫的 setprecison 固定輸出的小數點位數。使用時間約為 2 ms,記憶體約為 352 kB,通過測試。
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
ios::sync_with_stdio(0); cin.tie(0);
int n; cin >> n; // 人數
for(int i=0; i<n; i++) { // 執行 n 次
int g, a, h, w; cin >> g >> a >> h >> w; // 性別、年齡、身高、體重
float bmr;
if (g == 1) bmr = 13.7*w + 5.0*h - 6.8*a + 66.0; // 男
else bmr = 9.6*w + 1.8*h - 4.7*a + 655.0; // 女
cout << fixed << setprecision(2) << bmr << "\n";
}
return 0;
}
使用 cstdio 函式庫的 scanf 及 printf,採用 C 語言的語法。使用時間約為 2 ms,記憶體約為 96 kB,通過測試。
#include <cstdio>
using namespace std;
int main() {
int n; scanf("%d", &n); // 人數
for(int i=0; i<n; i++) { // 執行 n 次
int g, a, h, w; scanf("%d %d %d %d", &g, &a, &h, &w); // 性別、年齡、身高、體重
float bmr;
if (g == 1) bmr = 13.7*w + 5.0*h - 6.8*a + 66.0; // 男
else bmr = 9.6*w + 1.8*h - 4.7*a + 655.0; // 女
printf("%.2f\n", bmr);
}
return 0;
}
沒有留言:
張貼留言