#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类的声明 实现 使用 降序输出
输出120以内的质数(用StackofIntegers类)
最新推荐文章于 2022-03-13 19:50:42 发布