演算法-------統計數字問題
阿新 • • 發佈:2019-02-07
統計數字問題
一本書的頁碼重自然數1開始順序編碼直到自然數n。書的頁碼按照通常的習慣編排,每個頁碼都沒有多餘的前導數字0。
要求,給一個輸入檔案,統計他的頁碼(為了方便起見,假定每一行為一頁)。
然後,計算出書的全部頁碼用了多少次0,1,2,3...9。 最後將結果儲存至輸出檔案。
例如:
the number 4 shows up 1 times
the number 5 shows up 1 times
the number 6 shows up 1 times
the number 7 shows up 1 times
the number 8 shows up 1 times
the number 9 shows up 1 times
程式如下:
要求,給一個輸入檔案,統計他的頁碼(為了方便起見,假定每一行為一頁)。
然後,計算出書的全部頁碼用了多少次0,1,2,3...9。 最後將結果儲存至輸出檔案。
例如:
input.txt 檔案有 11 行
那麼,輸出檔案顯示:
the total pages of the book is 11 the number 0 shows up 1 times the number 1 shows up 4 times the number 2 shows up 1 times the number 3 shows up 1 times程式如下:
//sf_1.cpp //inout a file ,check how many lines does it have? //check how many times does the number "0,1,2...9" shows up? //October 23th, 2012 //created by Fish
#include<iostream> #include<fstream> #include<stdexcept> #include<sstream> #include<math.h> using namespace std; //open file function ifstream &open_file(ifstream &in, string &file) { in.close(); in.clear(); in.open(file.c_str()); return in; } //count 一個數有多少位 int count_num(const int n) { int count=1,t=10; while(n/t){ t*=10; ++count; } return count; } // 顯示數字出現的次數 void show_times(const int n) { int times[10]={0}; //定義陣列times,儲存0.。。9出現次數 int t=10; for(int i=1;i<=n;i++){ int m=i; int countNum=count_num(m); for(int p=0;p<countNum;p++){ for(int j=0;j<10;++j){ if(j==m%t) ++times[j]; } m=m/t; } } ofstream out; string file2; cout<<"please input the outfile name"<<endl; cin>>file2; out.open(file2.c_str()); out<<"the total pages of the book is "<<n<<endl<<endl;//輸出行數到 output檔案 cout<<"the total pages of the book is "<<n<<endl<<endl;//輸出行數到 命令控制檯 for(int i=0;i<10;++i){ out<<"the number "<<i<<" shows up "<<times[i]<<" times"<<endl;//輸出times[]到 output檔案 cout<<"the number "<<i<<" shows up "<<times[i]<<" times"<<endl;//輸出times[]到 命令控制檯 } } int main() { ifstream in; string file; int count=0; cout<<"plesase input the file you wanna open:"<<endl; cin>>file; open_file(in, file); if(!in) throw runtime_error("cannot open the file"); while(getline(in, file)) ++count; //count儲存的是行 show_times(count); return 0; }