作业帮 > 综合 > 作业

C++ 给出任意一个整数n,计算出 从1到n中所有数中1出现的次数

来源:学生作业帮 编辑:作业帮 分类:综合作业 时间:2024/08/25 20:09:41
C++ 给出任意一个整数n,计算出 从1到n中所有数中1出现的次数

#include <iostream>
#include <sstream>
#include<string>

using namespace std;

int main()
{
cout<<"input the n "<<endl;
int n;
cin>>n;
    for(int i=1;i<n+1;i++)
    {
    ostringstream os;
    os<<i;
    string temp=os.str();
     int count=0;
    for(int j=0;j<temp.length();j++)
    {
      if(temp[j]=='1')
      count++;

    }
    cout<<i<<"has size of 1 "<<count<<endl;
    }
    cout << "Hello world!" << endl;
    return 0;
}