当前位置:编程学习 > C/C++ >>

c++死循环问题

为何粗体部分continue会成为死循环

程序目的,计算a+aa+……+aaa…a的结果,a为整数,n为最后一项a的个数

#include<iostream>
#include<cmath>
using namespace std;
void main()
{
 int a,n;
 float aa=a%1;
 float nn=n%1;
 
 while (true)
 {
  cout<<"please enter the \"a\" and \"n\":"<<endl;
     cout<<"a must be a number in the range of 0 ~ 9."<<endl;
     cout<<"n must be a positive whole number"<<endl<<endl;
     cout<<"a=";
     cin>>a;
     cout<<"n=";
     cin>>n;
     if (a>=0&&a<=9&&n>0&&aa==0&&nn==0)
  {
        unsigned long result=0;
     unsigned long next=0;
        for (int i=0;i<n;++i)
     {
     next+=a*pow(10,i);
        result+=next;
    
     }
        if (result<=0)
     {
         cout<<"the result is overflowed,please enter again:"<<endl;
         continue;
     }
     else
     {
      cout<<"the result is "<<result<<endl<<endl;
      continue;
     }
  }
  else
  {
   cout<<"the a or n you entered was illegal,please enter again:";
   continue;
  }
  
    }
}

追问:但while循环内有cin,遇到cin时系统不是应该等待输入吗,但运行时它没有等待输入,而是一直打印cout的东西

答案:别说加不加continue
你while(true)本来就是死循环,除非遇到break语句才会终止,否则,不管有没有continue都一样。

你说的“死循环”是什么意思啊?这个程序不是你自己设计的么?如果条件(a>=0&&a<=9&&n>0&&aa==0&&nn==0)不满足,那么粗体continue就是让你再计算一次啊。

如果你想在得出一个正确的结果后结束程序,你可以添加一些控制条件的啊

上一个:C++ 困惑 C++ 困惑
下一个:C和C++有什么本质区别?

CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,