实现一个类,类中实现一个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;
}