#include<iostream.h>
#include<conio.h>
int Sum1(int n)
{
int count = 0; //记录1的个数
int factor = 1; //标记,逐位计算1的个数
int Lower = 0;
int Curr = 0;
int Higher = 0;
while ( n/factor != 0) //每次计算Lower Curr Higher的值
{
Lower = n - (n/factor) * factor;
Curr = (n/factor) % 10;
Higher = n / (factor*10);
switch (Curr)
{
case 0:
count += Higher * factor;
break;
case 1:
count += Higher * factor + Lower +1;
break;
default:
count += (Higher +1)*factor;
break;
}
factor *= 10;
}
return count;
}
int main()
{
int num;
int jixu;
cout<<"请输入要搜索的整数:"<<endl;
cin>>num;
cout<<"从1到此整数出现的1的个数为:"<<Sum1(num)<<endl;
cout<<"是否要继续测试:(0,退出 1,继续)"<<endl;
cin>>jixu;
if(jixu==1)
{
cout<<endl;
main();
}
else
{
return 0;
}
getch();
return 0;
}
四,程序运行
五,实验总结:
这次课堂练习老师拿出课上的时间让我们一起找规律,相当于告诉了我们实验思路。有了具体的思路,接下来做题就比较顺畅了,加上与小伙伴的讨论,于是做出来实验。