关于i的循环,又出现了i/=10,因此陷入了死循环。
可另设正整数k,令k=i
#include
using namespace std;
int main()
{
int n,k,temp,cnt=0;
cin>>n;
for(int i=1;i<=n;i++)
{
k=i;
while(k)
{
temp=k%10;
if(temp==1)
cnt++;
cout<k/=10;
}
}
cout<<"出现1的次数为:"<return 0;
}
更改后的程序,自己对照这找问题
#include
using namespace std;
int main()
{
int n,temp=0,cnt=0,res;
cin>>n;
for(int i=1;i<=n;i++)
{
temp=i;
while(temp>0)
{
res=temp%10;
if(res==1) cnt++;
temp=temp/10;
}
}
cout<<"出现1的次数为:"<
}
另外,其实这个算法的复杂度太高了,接近O(n2),有更优的算法