Question from Skiena's Programming Challenges. Getting WA (wrong answer) in Online Judge even though it's working for sample test cases. Can somebody find a case where it fails?
I tried the tricky case from this link and it gave the right answer-
"The Trip" challenge from Programming Challenges
Input
Standard input will contain the information for several trips. Each trip consists of a line containing a positive integer n denoting the number of students on the trip. This is followed by n lines of input, each containing the amount spent by a student in dollars and cents. There are no more than 1000 students and no student spent more than $10,000.00. A single line containing 0 follows the information for the last trip.
Output
For each trip, output a line stating the total amount of money, in dollars and cents, that must be exchanged to equalize the students’ costs.
Sample Input
3
10.00
20.00
30.00
4
15.00
15.01
3.00
3.01
0
Sample Output
$10.00
$11.99
#include <iostream>
#include <vector>
#include <sstream>
using namespace std;
int main()
{ vector <float> nums;
int numStudents,loopVar1,pos;
float amount,sum=0,roundAmt,ans;
string strAns;
stringstream ss;
while(cin>>numStudents) {
if(numStudents==0)
break;
ans=sum=0;
nums.erase(nums.begin(),nums.end());
for(loopVar1=0;loopVar1<numStudents;loopVar1++) {
cin>>amount;
nums.push_back(amount);
sum+=amount;
}
sum/=numStudents;
roundAmt=(int)(sum*100);
roundAmt/=100.0f;
//cout<<roundAmt<<"\n";
for(loopVar1=0;loopVar1<numStudents;loopVar1++)
if(nums[loopVar1]<roundAmt)
ans+=(roundAmt-nums[loopVar1]);
strAns="";
ss.str("");
ss<<ans;
strAns=ss.str();
pos=strAns.find('.');
if(pos==-1)
strAns+=".00";
else
strAns.erase(pos+3);
cout<<'$'<<strAns<<"\n";
}
return 0;
}
improving code that your think works
fits very well to this code (without ther
). \$\endgroup\$static_cast<int>(f + 1e-6)
(or use aconst double EPS = ...;
type thing so you can change it easily in a centralized place). \$\endgroup\$