五一假期—home

文章介绍了如何在C++中创建一个名为Myfun的类,包含set、Sum、Product、PrimeNumber等成员函数,以及使用类A和类B实现数字和字母交替输出。还展示了如何使用list容器和处理字符串下标越界异常。
摘要由CSDN通过智能技术生成

实现一个类,类中实现一个set函数,设置一个成员a的值。

实现Sum函数,打印1~成员a的值之间所有数字之和

实现Porduct函数,打印1~a的值之间所有数字的乘积

实现函数 PrimeNumber,输出1~a的值之间的所有质数

例如,调用set输入5,sum结果15,Porduct结果120,PrimeNumber结果2,3,5

#include <iostream>
#include <iomanip>
using namespace std;
class Myfun
{
    int a;
public:
    void Set(int a)
    {
       this->a=a;
    }
    void Sum()
    {
        int sum=0;
        for(int i=1;i<=a;i++)
        {
            sum+=i;
        }
        cout << "和为:" << sum << endl;
    }
    void Product()
    {
        int arr=1;
        for(int i=1;i<=a;i++)
        {
            arr=arr*i;
        }
        cout << "乘积为:" << arr << endl;
    }
    void PrimeNumber()
    {
        cout << "a以内的质数有:";
        int brr=0;
        for(int i=2;i<=a;i++)
        {
            for(int n=2;n<=i;n++)
            {
                int temp=i%n;
                if(temp==0)
                {
                    brr++;
                }
            }
            if(brr==1)
            {
                cout << setw(4) << left << i;
            }
            brr=0;
        }
    }
};

int main()
{
    int m;
    cin >> m;
    Myfun m1;
    m1.Set(m);
    m1.Sum();
    m1.Product();
    m1.PrimeNumber();
    return 0;
}

2.写一个程序,程序包含两个类,类中实现一个成员函数,MyGetChar(),类A中每调用次,按顺序得到一个数字字符,比如第一次调用得到0',第二次得到'1',以此类推,类B没调用一次得到一个小写字母字符,比如第一次调用得到'',第二次得到',以此类推,程序通过交替调用类A和类B的函数,实现运行结果输出一串字符串“0a1b2c3d4e5f6g7h8i9j0k112m3n4o5p6q7r8s9tuvwxyz

#include <iostream>

using namespace std;
class Word
{
    char a='a';
public:
    void MyGetChar()
    {
        cout << a;
        a+=1;
    }
    char show(char a)
    {
        a=this->a;
        return a;
    }
};
class number
{
    int a=0;
public:
    void MyGetChar()
    {
        cout << a;
        a+=1;
        if(a==9)
        {
            a=0;
        }
    }
};

int main()
{
    Word w1;
    number n1;
    char a=0;
    while(w1.show(a)<='z')
    {
        n1.MyGetChar();
        w1.MyGetChar();
    }
    return 0;
}

结果图

实现list容器

#include <iostream>
#include <list>
using namespace std;

int main()
{
    list<int> myList = {1, 2, 3, 4, 5};
    for (const int& num : myList)
    {
        cout << num << " ";
    }

    return 0;
}

已知C风格的字符串,完成对字符串通过下标访问时的异常处理机制(越界访问)

#include <iostream>

using namespace std;
void fun(int a,string s1)
{
    cout << s1.at(a) << endl;
}
int main()
{
    string s1;
    int a;
    cin >> s1 >> a;
    fun(a,s1);
    try {
        fun(a>s1.size(),s1);
    } catch (int ret) {
        if(ret>s1.size())
        {
            cout << "位置不合理" << endl;
        }
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值