C++小练习(一)
来源:互联网 发布:ubuntu apt 安装路径 编辑:程序博客网 时间:2024/05/16 19:18
1.建立一个类Prime,用来判断某整数是否为素数。具体要求如下:
(1)私有数据成员
int n:存放某个整数。
(2)公有成员函数
void set(int _n):将数据成员n的值设置为参数_n的值。
int IsPrime():判断数据成员n是否为素数,是素数则返回1,否则返回0。
void print():如果n为素数(通过成员函数IsPrime判断),则输出”n is a prime number.”,否则输出”n is not a prime number.”。
(3)在主函数中对该类进行测试。
定义类Prime的对象p。
调用对象p的set成员函数,设置p的数据成员n为7。
调用对象p的print成员函数,输出判断结果。
设置p的数据成员n为9。
输出判断结果。
本程序正确的输出结果为:
7 is a prime number.
9 is not a prime number.
示例代码:
#include <iostream>using namespace std;class Prime{private: int n;public: void set(int _n); int IsPrime(); void print();};void Prime::set(int _n){ n = _n;}int Prime::IsPrime(){ int i; for (i = 2; i <= n / 2; i++) { if (n % i == 0) //% { return 0; } } return 1;}void Prime::print(){ int i = IsPrime(); if (i != 0) { cout << n << " is a prime number." << endl; } else { cout << n << " is not a prime number." << endl; }}int main(){ Prime p; p.set(7); p.print(); p.set(`); p.print(); system("pause"); return 0;}
阅读全文
0 0
- C语言--------------字符串小程序练习(一)
- Python小练习(一)
- JSP小练习(一)
- XML小练习(一)
- python小练习(一)
- C++小练习(一)
- 一天练习一个小C/C++程序(一) 控制台版“金山打字”游戏
- OpenGL小练习一
- 一、JNI 小练习
- Python小练习一
- 小练习一
- scala小练习一
- c语言小练习(1)
- 第十九章,指针小练习(C++)
- C语言小练习
- C小练习
- C 小练习
- c语言小练习
- Python汉译英小程序
- VS2015中的建模
- MATLAB实现双线性内插算法
- Ubuntu 10.04下Qt4.7.4移植详解
- WebSphere 安装部署,发布web应用
- C++小练习(一)
- ubuntu 16.04 安装genymotion
- android 持久化技术(一)文件存储
- leetcode 168|171. Excel Sheet Column Title 171. Excel Sheet Column Number
- NO.1 Spring IOC 先建一个简单工厂
- 修改genymotion的deviceId
- LeetCode 14 — Longest Common Prefix (Java)
- HDOJ2018 母牛的故事
- ActiveMQ的消息队列的介绍