【问题标题】:how can i calculate average from a string contains numbers and letters?如何从包含数字和字母的字符串中计算平均值?
【发布时间】:2013-09-17 09:30:00
【问题描述】:

函数应该接受一个字符串参数

string return_average(string x)

并返回一个整数或双精度值作为平均值..

我得到了奇怪的结果:例如,当我通过 123abc 时,它返回 50 而不是 2(三个数字的平均值 (1,2,3).. 有什么想法吗?这里是代码:

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;
}

【问题讨论】:

    标签: c++ string int average


    【解决方案1】:

    您添加的是字符代码(很可能是 ASCII 代码)而不是数值。变化:

        n+=(int)c;    // accumulate character code
    

    到:

        n+=(c - '0'); // convert character to numeric value and accumulate
    

    注意:如果您尝试在调试器中单步执行您的代码,问题将立即显而易见,因为 n 会以较大的值(49、50、51)而不是预期值(1 , 2, 3)。

    【讨论】:

      【解决方案2】:

      是的,您正在添加 ASCII 值,因为从 123abc 的输出中可以看到它返回 50=((49+50+51)/3) 记住 (int)c 将 'c' 转换为它的 ASCII 值 因此,您可以从 n 中删除 48(ASCII 值为 0)或执行 n+=(c - '0');

      【讨论】:

        【解决方案3】:

        对于字符使用 n+=(c-'0') 而不是 n=(int)c

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2022-01-15
          • 1970-01-01
          • 1970-01-01
          • 2021-09-25
          • 2015-10-15
          • 2021-12-11
          • 1970-01-01
          相关资源
          最近更新 更多