【无标题】

本文介绍了三个C++编程作业示例,涉及类A和B的构造、成员函数(如求和、质数判断、字符处理和字符串操作),展示了如何在主函数中调用这些方法并进行相应操作。
摘要由CSDN通过智能技术生成

作业1:

运行代码:
#include <iostream>
using namespace std;

class A{
    int a;
public:
    A(int a):a(a){}
    void Sum();
    void Product();
    void PrimeNumber();
};
void A::Sum(){

    int i=0;
    int sum=0;
    while(i<a){
       i++;
       sum+=i;
    }
    cout<<"sum=="<<sum<<endl;

}
void A::PrimeNumber(){
    int i,j;
    for(i=1;i<=a;i++){
        for(j=2;j<i;j++){
            if(i%j==0){
                break;
            }
        }
        if(j==i || i==1){cout<<i<<" ";}
    }
    cout<<endl;
}
void A::Product(){
    int i=0;
    int pro=1;
    while(i<a){
        i++;
        pro*=i;
    }
    cout<<"pro=="<<pro<<endl;
}

int main()
{
    A a(10);
    a.Sum();
    a.Product();
    a.PrimeNumber();
    return 0;
}
运行截图:

作业2:

运行代码:
#include <iostream>
using namespace std;
class A{
    char a;
    int num;
public:
    A():a('0'),num(0){}
    char MyGetChar();
};
char A::MyGetChar(){

    if(a >'9'){
        num++;
        a='0';
    }
    if(num==2){
        return 0;
    }
    return a++;

}
class B{
    char b;
public:
    B():b('a'){}
    char MyGetChar();
};
char B::MyGetChar(){
    if(b >'z'){
        return 0;
    }
    return b++;
}

int main()
{
    B b1;
    A a1;
    char a,b;

    while(1){
    a=a1.MyGetChar();
    b=b1.MyGetChar();
    if(a==0&&b==0){break;}
        if(a!=0){
            cout<<a;
        }
        if(b!=0){
            cout<<b;
        }
    }
    putchar(10);
    return 0;
}
运行截图:

作业3:

运行代码:
#include <iostream>

using namespace std;
class A{
    string a;
public:
    void put(char a){
        (this->a)+=a;
    }
    void dump(){
        cout<<"a="<<a<<endl;;
    }
};
class B{
    string b;
public:
    void put(char b){
        (this->b)+=b;
    }
    void dump(){
        cout<<"b="<<b<<endl;;
    }
};
int main()
{
    A a;
    B b;
    string str;
    cin>>str;
    int len = str.length();
    int i=0;
    while(i<len){
        char c = str.at(i);
        if(c<='z' && c>='a'){
            a.put(c);
        }else if(c<='9' && c>='0'){
            b.put(c);
        }
        i++;
    }
    a.dump();
    b.dump();
    return 0;
}
运行截图:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值