1.定义一个”数据类型” datatype类,能处理包含字符型、整型、浮点型三种类型的数据,给出其构造函数。
#include <iostream>
using namespace std;
class datatype{
enum{
character,
integer,
floating_point
} vartype;
union
{
char c;
int i;
float f;
};
public:
datatype(char ch) {
vartype = character;
c = ch;
}
datatype(int ii) {
vartype = integer;
i = ii;
}
datatype(float ff) {
vartype = floating_point;
f = ff;
}
void print();
};
void datatype::print() {
switch (vartype) {
case character:
cout << "字符型: " << c << endl;
break;
case integer:
cout << "整型: " << i << endl;
break;
case floating_point:
cout << "浮点型: " << f << endl;
break;
}
}
void test() {
datatype A('c'), B(12), C(1.44F);
A.print();
B.print();
C.print();
}
知识点:联合体、枚举类型的使用。
联合体公用一个存储空间值得至于的是sizeof(union);枚举类型则要注意枚举类型的值默认从0开始,但是如果前面指定了值,后面没有指定的要挨个比前面大1。
2.用穷举法找出1~100间的质数,显示出来
质数是除了一和它本身之外,不能被其他数整除的正整数,又称素数。100以内的质数有:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
合数是除了质数以外的数,即除了一和它本身以外,还有其他的因数的正整数。
区别在于因数的个数,质数只有2个因数,合数有多于2个因数。
1既不是质数,也不是合数。
//n是否为素数
bool is_prime(int n)
{
if (n < 2) // 1既不是质数,也不是合数。
return false;
for (int i = 2; i*i <= n; i++)
if (n % i == 0)
return false;
return true;
}
void test()
{
int cnt = 0;
cout << "质数如下:" << endl;
for (int i = 2; i <= 100; i++){
if (is_prime(i)){
cnt++;
cout << i << "\t";
}
if (cnt % 10 == 0) cout << endl;
}
cout << endl;
}
结果:
质数如下:
2 3 5 7 11 13 17 19 23 29
31 37 41 43 47 53 59 61 67 71
73 79 83 89 97
请按任意键继续. . .
3.在程序中定义一个整型变量,赋以1~100的值,要求用户猜这个数,比较两个数的大小,把结果提示给用户,直到猜对为止。
#include <ctime>
#include <iostream>
using