alabasi
alabasi

Reputation: 81

how can i calculate average from a string contains numbers and letters?

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

Answers (3)

Vivek Aditya
Vivek Aditya

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

Marsh
Marsh

Reputation: 173

For characters use n+=(c-'0') instead of n=(int)c

Upvotes: 0

Paul R
Paul R

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

Related Questions