算法-------统计数字问题

10 篇文章 0 订阅
统计数字问题
一本书的页码重自然数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 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;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值