输出120以内的质数(用StackofIntegers类)


#ifndef STACKOFINTEGERS_H
#define STACKOFINTEGERS_H
using namespace std;
class StackofIntegers
{
private:
int elements[1000];
int size_;
public:
StackofIntegers();
public:
bool isempty();
int peek();
void push(int value);
int pop();
int getSize();
};
#endif

#include"StackofIntegers.h"
using namespace std;
StackofIntegers::StackofIntegers()
{
    size_=0;
};
bool StackofIntegers::isempty()
{
    return(size_==0);//空就返回1 
};
int StackofIntegers::peek()
{
return elements[size_-1]; 
};
void StackofIntegers::push(int value)
{
   elements[size_]=value;
   size_++;
   //elements[size_++]=value;
};
int StackofIntegers::pop()
{
  /*int t= elements[size_];
  size_=size_-1;
  return t;*/  
  size_=size_-1;
  return elements[size_];//注意前自增 后自增 前自减 后自减 
};
int StackofIntegers::getSize()
{
return size_;
};

#include<iostream>
#include"StackofIntegers.h"
using namespace std;
int main(void){


const int limit=120;
int number=2;
StackofIntegers StackofPrimes;


while(number<=limit)
{
        bool isPrime=true;
        for(int divisor=2;divisor<=number/2;divisor++)
        {
            if(number%divisor==0)
            {
                isPrime=false;
            break;
            }
        }
        if(isPrime)
        {
            StackofPrimes.push(number);
        }
        number++;
}


 int amount=StackofPrimes.getSize();
 int counter =0;
 cout<<"输出120以内的质数:" <<endl;
        while(!StackofPrimes.isempty())
        {
        cout<<StackofPrimes.pop()<<" ";
      counter++;
            if(counter%10==0)
            cout<<endl; 
      }
      cout<<"数量:"<<amount<<endl; 
     return 0; 
}






//学到了:
//1.如何判断素数
//2.循环 判断条件的使用
//3.stack类的声明 实现 使用 降序输出 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值