算法-------统计数字问题
来源:互联网 发布:卡戴珊臀部 知乎 编辑:程序博客网 时间:2024/06/05 07:15
统计数字问题
一本书的页码重自然数1开始顺序编码直到自然数n。书的页码按照通常的习惯编排,每个页码都没有多余的前导数字0。要求,给一个输入文件,统计他的页码(为了方便起见,假定每一行为一页)。
然后,计算出书的全部页码用了多少次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
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
程序如下:
//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 functionifstream &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;}
- 算法-------统计数字问题
- 统计数字问题算法
- 统计数字问题算法1
- 算法设计:统计数字问题
- 算法1 —统计数字问题
- 算法1-1:统计数字问题
- 统计数字问题-算法实现(暴力统计法)
- 统计数字问题[算法设计与分析]
- 每日学习一算法【1】统计数字问题
- 算法分析与设计之统计数字问题
- 统计数字问题
- 统计数字问题
- 统计数字问题
- 统计数字问题
- 统计数字问题
- 统计数字问题
- 统计数字问题
- 统计数字问题
- Your display is too small to run Menuconfig!
- 两个小项目--表决器
- 万以内的回文素数
- 数万中国人上网免费读美国大学
- jquery异步请求返回json串
- 算法-------统计数字问题
- 多Linux操作系统安装方法
- ThreadLocal的设计与使用
- 《php---mysql简单应用---在线词典》
- Red5+OpenOffice+OpenMeetings架设视频会议网络
- 处理ArithmeticException异常!!!
- CppUnit
- mastudio 表格
- JavaScript跨域总结与解决办法