Reputation: 81
the function should take a string argument
string return_average(string x)<---let's assume we passed("abc678") to the function
and return an integer or double value as an average..
am getting weird results : for example when I pass 123abc it returns 50 instead of 2 (the average of the three numbers (1,2,3).. any ideas ? here is the code :
int retav(string x)
{
int k=0;
int average=0;
int j=0;
int n = 0;
char c='a';
string mySt = x;
int L = mySt.length()-1;
for(int i=0;i<=L;i++)
{
c = mySt.at(i);
if(isdigit(c))
{
n+=(int)c;
j++;
}
}
average = n/j;
return average;
}
Upvotes: 2
Views: 2039
Reputation: 1173
Yes You are adding ASCII values as it is visible from your output of 123abc returning 50=((49+50+51)/3) Remember (int)c cast 'c' into its ASCII value hence you can either remove 48(ASCII value of 0) from n or do n+=(c - '0');
Upvotes: 2
Reputation: 213029
You're adding character codes (most likely ASCII codes) rather than numeric values. Change:
n+=(int)c; // accumulate character code
to:
n+=(c - '0'); // convert character to numeric value and accumulate
Note: if you had tried stepping through your code in a debugger the problem would have been immediately obvious, since n
would have been incrementing by large values (49, 50, 51) rather than by the expected values (1, 2, 3).
Upvotes: 4