解法一、stringstream
✅ 完整代碼
評分結果(參考) : AC (2ms, 360KB)
#include <bits/stdc++.h>
using namespace std;
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
string s;
int num;
char c;
double val;
while(getline(cin,s)){
stringstream ss(s);
int n;
double ans = 0;
while(ss >> num >> c >> val){
if(num & 1) ans += val;
else ans -= val;
}
cout << ans << "\n";
}
return 0;
}
解法二、手動處理字串
✅ 完整代碼
評分結果(參考) : AC (2ms, 360KB)
#include<bits/stdc++.h>
using namespace std;
int i;
string s;
double getF(){
double res = 0;
int neg = 1;
if(s[i] == '-'){
i++;
neg = -1;
}
for(; i<s.size() && s[i]!='.' && s[i]!=' '; i++){
res = res*10 + (s[i]-'0');
}
if(i>=s.size() || s[i]==' ') return res*neg;
double d = 0.1;
for(i+=1; i<s.size() && s[i]!=' '; i++){
res += (s[i]-'0')*d;
d *= 0.1;
}
return res*neg;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
while(getline(cin, s)){
double ans = 0;
i = 0;
while(i<s.size()){
while(s[i] != ':') i++;
i++;
if((s[i-2]-'0') & 1) ans += getF();
else ans -= getF();
}
cout << ans << "\n";
}
return 0;
}