日期:2026年5月11日
ZeroJudge 題目連結:d018. 字串讀取練習
解題想法
這題的輸出格式對 Python 使用者而言很麻煩,答案如果是小數,輸出的位數不固定,而且要捨去後面的0;如果是整數則連小數點都不能輸出。後來是將相減的結果先轉成字串,再用 rstrip('0') 去除後方的 0,再接著用 rstrip('.') 去除後方的小數點,如果答案是小數,此時字串最後面是數字,小數點不會被刪除。
Python 程式碼
使用時間約為 15 ms,記憶體約為 8.4 MB,通過測試。
def format_float(num):
return f"{num:.6f}".rstrip('0').rstrip('.')
while True:
try:
data = input().split()
even, odd = 0, 0
for d in data:
k, v = d.split(':')
k = int(k)
v = float(v)
if k%2 == 0: even += v
else: odd += v
ans = format_float(odd - even)
print(ans)
except EOFError:
break
C++ 程式碼
使用時間約為 1 ms,記憶體約為 3.6 MB,通過測試。
#include <iostream>
#include <sstream>
using namespace std;
int main() {
ios::sync_with_stdio(0); cin.tie(0);
string s;
while(getline(cin, s)) {
stringstream ss (s);
double even = 0.0, odd = 0.0;
while(ss >> s) {
size_t idx = s.find(":");
int k = stoi(s.substr(0, idx));
double x = stod(s.substr(idx+1));
if (k%2 == 0) even += x;
else odd += x;
}
cout << odd - even << "\n";
}
return 0;
}
沒有留言:
張貼留言