数据结构 求平均值

来源:百度知道 编辑:UC知道 时间:2024/09/28 15:41:45
给定了一排数据 比如说1,2,3,4,5,6,7,..50 或者说str= 1,2,3,4,5,6,7,...50
然后读取这串数据,包括逗号(比如说是从INI 中读取的这串数据),然后从中提取数字 求其平均值,谢谢了~ 最好用C 或者C++
用伪C 描述也可以 .....
最好能用数据结构中串的方法来解答

char *ch = str;
int j = 0;
int k = 0;
for(i=0; i <strlen(str); i++)//把所有数字读到数组a中
{
if(ch != ',' ){ch++;continue;}
else{getnum(j,i,a[k])(起始索引截取字符串);j=i+1;k++;}

}
average = sum(a)/(k+1);

[15@c-cpp]$ cat test.cpp
#include <iostream>
#include <sstream>
#include <string>
#include <algorithm>
using namespace std;
int main ()
{
string str("1,2,3,4,5,6,7,50");
replace(str.begin(), str.end(), ',' , ' ');
istringstream iss(str, istringstream::in);
int val, sum = 0, cnt = 0;
while (iss >> val)
sum += val, cnt++;
cout << "average: " << (double)sum/(double)cnt << endl;
return 0;
}
[16@c-cpp]$ g++ =Wall test.cpp
g++: =Wall:没有该文件或目录
[17@c-cpp]$ g++ -Wall test.cpp
[18@c-cpp]$ ./a.out
average: 9.75

int sum=0,avg=0;
int c