1.将int转为string string转int方法
#include<iostream> #include "sstream" // #include<string> #include <stdio.h> using namespace std; int pagecount(int n){ int num[10] = {0}; for(int i = 1; i<=n;i++){ stringstream ss; ss << i; string s1 = ss.str(); cout<<endl; for (int j = 0;j<s1.length();j++){ int b; stringstream os; os << s1[j]; os >> b; cout<<endl; num[b] = num[b] + 1; } } for(int i = 0; i < 10;i++) cout<<i<<":"<<num[i]<<endl; } int main(){ int page; cout<<"输入页数:"; cin>>page; pagecount(page); }
2.取余法
void pageCount(){ int n; int a[10] = {0}; cout << "请输入要计算的页码: "; cin >> n; for (int i = 1; i <= n; i++){ int k=i; while(k) { a[k%10]++; k = k/10; } } for (int i = 0; i < 10; i++) cout << i << ": " << a[i] << endl; }