1.定义一个”数据类型” datatype类,能处理包含字符型、整型、浮点型三种类型的数据,给出其构造函数。()
#include <iostream.h>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 main() {datatype A('c'), B(12), C(1.44F);A.print();B.print();C.print();}
程序运行输出:字符型: c整型: 12浮点型: 1.44
2.用穷举法找出1~100间的质数,显示出来
使用while循环语句: #include <iostream.h> #include <math.h>
void main() { int i,j,k,flag; i = 2;while(i <= 100) { flag = 1; k = sqrt(i); j = 2; while (j <= k) {