关于一个素数的c++程序的思考

#include<iostream>
using namespace std;
int main()
{
      int a,b;
      char c;
      cout<<"Enter a number:";
      cin>>a;
      for(b=2;b<=a/2;b++)
      if(a%b==0)
      {
          cout<<"the number is not a prime!"<<endl
              <<"第一个除数 is:"<<b<<endl;
          exit(0);
       }
      cout<<"the number is a prime!"<<endl;
      return 0;
}

本来课本上是这个程序,我想让他达到:如果输入一个数是素数,就输出“the number is a prime!”结束这个程序;如果输入的数不是素数,就输出“the number is not a prime!”和“第一个除数 is:xxx”,并且出现“是否继续的询问?”,这时候如果输入y,就继续出现"Enter a number:",如果输入n,则程序也结束。

为了达到上面的功能,我想了很多办法,最后别逼无奈还是使用goto语句才实现了功能:

#include<iostream>
using namespace std;
int main()
{
 int a,b;
 char c;
 chang:cout<<"Enter a number:";
 cin>>a;
 for(b=2;b<=a/2;b++)
 if(a%b==0)
   {
    cout<<"the number is not a prime!"<<endl
        <<"chushu is:"<<b<<endl;
    break;
   }
  if(b==a/2+1)
     cout<<"the number is a prime!"<<endl;
  else
  {
      cout<<"does it continue?";
      cin>>c;
      while(c!='n')
      goto chang;
   }
 return 0;
}

这个判断是否继续的部分与输出输出是素数和判断素数的过程都有关:要怎么实现判断后回程序的开头(用到判断素数的部分),又要实现当是素数时直接跳出呢(也用到判断素数的部分)?

现在还没有想出不用goto的实现方法,想到后待更新........

原文链接: https://www.cnblogs.com/qlwy/archive/2011/06/30/2121915.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    关于一个素数的c++程序的思考

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/27897

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月8日 上午5:28
下一篇 2023年2月8日 上午5:29

相关推荐