C++例题练习(2)

环境:Dev-C++( Version:5.6.1)

1.循环输入一个1-1000的整数,判断是否为素数(输入1时程序结束)

  素数:只能被1和自身整除.

  实现代码:

#include <iostream>
#include <cstdlib>
#include <cassert>
using namespace std;
/*
*function name:isPrimeNumber.
*precondition:parameter value is more than zero and less than or equal one thousand.
*postcondition:return true when parameter value is prime number.
*/
bool isPrimeNumber(const int &number); int main()
{
while(true)
{
int number;
cout<<"please input a integer number(0-1000):"<<endl;
cin>>number;
//condition
assert(number>&&number<=);
if(number == ) {
break;
} bool flag;
flag = isPrimeNumber(number);
if(flag) {
cout<<"yes, the number is prime number."<<endl;
} else {
cout<<"no, the number is not prime number."<<endl;
}
}
return EXIT_SUCCESS;
}
bool isPrimeNumber(const int &number)
{
for(int i=;i<number/+;i++) {
if(number%i == ) {
return false;
}
}
return true;
}

2.用类来实现输入和输出时间(时:分:秒)

要求:将数据成员改为私有;将输入和输出的功能有成员函数实现;在类体内定义成员函数

代码实现:

(对于时间输入的合理性,简单的采用断言assert函数来进行处理,不合理,程序直接结束运行)

 #include <iostream>
#include <cstdlib>
#include <cassert>
using namespace std;
class Time
{
public:
void set_time()
{
cout<<"hour(0-23):"<<endl;
cin>>hour;
assert(hour>&&hour<); cout<<"minute(0-59):"<<endl;
cin>>minute;
assert(minute>&&minute<); cout<<"second(0-59):"<<endl;
cin>>sec;
assert(sec>&&sec<);
}
void show_time()
{
cout<<"time:"<<endl;
cout<<hour<<":"<<minute<<":"<<sec<<endl;
}
private:
int hour;
int minute;
int sec;
};
int main()
{
Time t;
t.set_time();
t.show_time();
return EXIT_SUCCESS;
}

3.在上题的基础上进行修改:在类体内声明成员函数,而在类外定义成员函数

  代码实现:

 #include <iostream>
#include <cstdlib>
#include <cassert>
using namespace std;
class Time
{
public:
void set_time();
void show_time();
private:
int hour;
int minute;
int sec;
};
void Time::set_time()
{
cout<<"hour(0-23):"<<endl;
cin>>hour;
assert(hour>&&hour<); cout<<"minute(0-59):"<<endl;
cin>>minute;
assert(minute>&&minute<); cout<<"second(0-59):"<<endl;
cin>>sec;
assert(sec>&&sec<);
}
void Time::show_time()
{
cout<<"time:"<<endl;
cout<<hour<<":"<<minute<<":"<<sec<<endl;
}
int main()
{
Time t;
t.set_time();
t.show_time();
return EXIT_SUCCESS;
}

4.求三个长方柱的体积

  由成员函数完成如下功能:

1>由键盘分别输入3个长方柱的长,宽,高;

       2>计算长方柱的体积;

3>输出3个长方柱的体积;

  实现代码:

 #include <iostream>
#include <cstdlib>
#include <cassert>
using namespace std;
class Box
{
public:
void set_box();
void volume()
{
cout<<"volume :"<<length*width*height<<endl;
}
private:
double length;
double width;
double height;
};
/*
*precondition:null
*postcondition:set instance data
*/
void Box::set_box()
{
cout<<"please enter the length, width and height of a rectangle:"<<endl;
cin>>length>>width>>height;
assert(length>&&width>&&height>);
}
int main()
{
Box box1;
box1.set_box();
box1.volume(); Box box2;
box2.set_box();
box2.volume(); Box box3;
box3.set_box();
box3.volume();
return EXIT_SUCCESS;
}
上一篇:linux 下 奇怪的 动态库 依赖问题


下一篇:POI2001 金矿