Median-求中位数,文件中数字升序排列:
//Median-求中位数,文件中数字升序排列 #include<iostream> #include<fstream> #include<cstdlib> int main() { using namespace std; ifstream fin; ofstream fout; double median,tem1,tem2; int count = 1; fin.open("numbers.dat"); if(fin.fail()) { cout<<"Input file opening failed.\n"; exit(1); } fin>>tem1; while(!fin.eof()) { count++; fin>>tem1; } cout<<count<<endl; fin.close(); fin.open("numbers.dat"); if(fin.fail()) { cout<<"Input file opening failed.\n"; exit(1); } if(count % 2) for(int i = 1;i <= (count/2+1);i++) fin>>median; else { for(int i = 1;i <= (count/2);i++) { fin>>tem1; } fin>>tem2; //cout<<tem1<<endl; //cout<<tem2<<endl; median = (tem1+tem2)/2; } cout<<"The median of the numbers is "<<median<<endl; fin.close(); return 0; }
文件1:
1 2 3 4 5 6
结果1:
6 The median of the numbers is 3.5
文件2:
1 2 3 4 5 6 7
结果2:
7 The median of the numbers is 4
原文地址:http://9320314.blog.51cto.com/9310314/1547769