1
cpp
#include <iostream>
#include <cmath>
using namespace std;
class A{
private:
int a;
// 判断一个数是否为质数
bool isP(int num) {
if (num<2) return false;
for (int i=2;i<=sqrt(num);i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
public:
// 构造函数
A():a(0){}
// 设置成员a的值
void set(int value) {
a = value;
}
// 计算并打印1到a之间所有数字的和
void Sum() {
int sum = 0;
for (int i = 1; i <= a; ++i) {
sum += i;
}
cout << "1 到 " << a << " 和 = " << sum <<endl;
}
// 计算并打印1到a之间所有数字的乘积
void Product() {
long long product = 1; // 使用long long防止乘积溢出
for (int i = 1; i <= a; ++i) {
product *= i;
}
cout << "1 到 " << a << " 乘积 = " << product <<endl;
}
// 输出1到a之间的所有质数
void PrimeNumber() {
cout << "1 到 " << a << " 中的质数 = ";
bool flag = true;
for (int i = 2; i <= a; ++i) {
if (isP(i)) {
if (!flag) {
cout << ",";
}
cout << i;
flag = false;
}
}
cout<<endl;
}
};
int main() {
A no;
int a=0;
cout<<"输入a:"<<endl;
cin>>a;
no.set(a);
no.Sum();
no.Product();
no.PrimeNumber();
return 0;
}
2
cpp
#include <iostream>
using namespace std;
class A{
private:
int count;
public:
A():count(0){}
char MyGetChar(){
if (count < 10){
return '0' + count++;
}else{
count = 0; // 重置计数
return '0' + count++;
}
}
};
class B{
private:
char count;
public:
B():count('a'){}
char MyGetChar(){
char ret = count;
count++;
if (count > 'z'){
count = 'a'; // 重置计数
}
return ret;
}
};
int main(){
A a;
B b;
for (int i=0;i<35;i++) {
if(i<20)
cout << a.MyGetChar();
if (i<26)
cout<<b.MyGetChar();
}
cout<<endl;
return 0;
}
3
cpp
#include <iostream>
#include <list>
using namespace std;
class A {
private:
list<char> n;
public:
void addNumber(char num) {
n.push_back(num);
}
void sortNumbers() {
n.sort();
}
void dump() {
cout << "存放数字的类,输出: ";
list<char>::iterator it;
for(it=n.begin();it!=n.end();it++) {
cout<<*it;
}
cout<<endl;
}
};
class B {
private:
list<char> l;
public:
void addLetter(char l) {
this->l.push_back(l);
}
void sortLetters() {
l.sort();
}
void dump() {
cout << "存放字母的类,输出: ";
list<char>::iterator it;
for(it=l.begin();it!=l.end();it++) {
cout<<*it;
}
cout<<endl;
}
};
int main() {
string input;
cout << "请输入一个字符串: ";
cin >> input;
A a;
B b;
for (int i = 0; i <static_cast<int>(input.size()); ++i) {
char c = input[i];
if (c >= '0' && c <= '9') {
a.addNumber(c);
} else if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
b.addLetter(c);
}
}
b.sortLetters();
a.sortNumbers();
b.dump();
a.dump();
return 0;
}