想看題目請點我
以下是小弟程式碼 ,
#include<iostream>
#include<math.h>
using namespace std;
int main() {
string str ;
while(getline(cin,str))
{
int no = 0 , status = 0 ;
double oddSum = 0 , evenSum = 0 , temp = 0 , pointCount = 0 ;
bool negative = false , point = false ;
for(int i = 0 ; i <= str.length() ; i++)
{
if(status==0) // 取 no
{
if(str[i]!=':')
no = no * 10 + (int)(str[i]-48) ;
else
status = 1 ;
}
else if(status==1) // 分析 值
{
if(str[i]=='-')
{
negative = true ;
i++ ;
}
if(str[i]==' ' || i==str.length()) // 分析是否加入總和
{
if((no%2)==0) // 偶數
{
if(negative==false)
evenSum += temp ;
else
evenSum -= temp ;
}
else
{
if(negative==false)
oddSum += temp ;
else
oddSum -= temp ;
}
// Init
no = 0 ;
temp = 0 ;
pointCount = 0 ;
status = 0 ;
negative = false ;
point = false ;
}
else if(str[i]!='.' && point!=true)
{
temp = temp * 10 + (int)(str[i]-48) ;
}
else
{
if(point==false) // 判斷是否小數第一位
{
i++;
}
pointCount++;
temp = temp + ((str[i]-48))/pow (10,pointCount) ;
point = true ;
}
}
}
cout << oddSum - evenSum << endl ;
}
}
以下是別人寫的 ,
相當的短 ,
值得學習阿(哭哭) ,
#include<iostream>
#include<algorithm>
using namespace std;
const int MAX=3000;
float arr[MAX];
int main() {
char ch[MAX];
char* ptr;
while(gets(ch))
{
int c=0;
float odd=0,even=0;
ptr=strtok(ch,": ");
while(ptr!=NULL)
{
arr[c++]=atof(ptr);
ptr=strtok(NULL,": ");
}
for(int i=0 ; i < c ; i+=2)
{
if(((int)arr[i])%2)
odd+=arr[i+1];
else
even+=arr[i+1];
}
cout << odd - even << endl;
memset(arr,0.0,MAX);
}
return 0;
}
這題有幾個重點提示 ,
小數可能不只一位 ,
且輸入的值可能有負數 ,
大致上就這些要注意 :P ,
P.S 多使用函式庫吧!! 高手寫的好短阿 >_<
早知也使用atof了