清明作业 c++

本文介绍了C++中如何通过类封装实现累加、阶乘计算、质数判断以及字符串交错输出的功能。通过实例展示了如何将字母和数字分别存储在不同类的对象中并进行显示。
摘要由CSDN通过智能技术生成

1.封装一个类,实现对一个数求累和阶乘质数 

#include <iostream>

using namespace std;
int mproduct(int a){
    if(a>1){
        return a*mproduct((a-1));
    }else{
        return 1;
    }
}
class number{
    int a;
public:
    number():a(5){};
    number(int a):a(a){}
    void set(int a){this->a=a;}
    void sum(){
        int sun=0;
        for(int i=1;i<=a;i++){
            sun+=i;
        }
        cout<<"sun="<<sun<<endl;
    }
    void product(){
        cout<<mproduct(a)<<endl;
    }
    void primeNumber(){

            for(int j=1;j<a;j++){
                if(a%j==0){
                    continue;
                }else{
                    cout<<j<<"  ";
                }
            }

        cout<<endl;
    }
};

int main()
{
    number num;
    num.set(12);
    num.sum();
    num.product();
    num.primeNumber();
    return 0;
}

2.封装两个类,实现字符串交错输出 

#include <iostream>

using namespace std;
class A{
    string str;
    int a;
public:
    A():str("abcdefghijklmnopqrstuvwxyz"),a(0){}
    void mygetchar(){
        cout <<str.at(a)<<"  ";
        a=(a+1)%26;
    }
};
class B{
    string str;
    int a;
public:
    B():str("1234567890"),a(0){}
    void mygetchar(){
        cout<<str.at(a)<<"  ";
        a=(a+1)%10;
    }
};

int main()
{
    A a;
    B b;
    int i=0;
    int len;
    cin>>len;
    while(i++<len){
        a.mygetchar();
        b.mygetchar();
    }
    return 0;
}

 

3. 输入字符串,将字母和数字分别存入两个不同的类的对象,然后输出。

#include <iostream>
#include<cstring>
#include<stdio.h>
using namespace std;
class A{
    string a;

public:
    A(){

    }
    void myinsert(char c){
        a+=c;
    }
    void show(){
        cout<<a<<endl;
    }
};
class B{
    string b;

public:
    B(){}
    void myinsert(char c){
        b+=c;
    }
    void show(){
        cout<<b<<endl;
    }
public:

};

int main()
{
    string str;
    A A;
    B B;
    //char a[128];
    cin>>str;
    cout<<"字符串输入成功"<<endl;
    for(unsigned int i=0;i<str.length();i++){
        if(str.at(i)<'9'&&str.at(i)>'0'){
            A.myinsert(str.at(i));
        }else{
            B.myinsert(str.at(i));
        }
    }
    A.show();
    B.show();
    return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值