求以下问题的完整代码,要求使用c++面向对象的程序设计方法和构造函数
定义两个数组,根据输入输出对应的字符就可以了
代码如下:
#include <iostream>
using namespace std;
class Trans
{
private:
int n;
public:
Trans(int _n):n(_n){}
void trans()
{
if (n == 1)
cout << "Spring";
else if (n == 2)
cout << "Summer";
else if (n == 3)
cout << "Fall";
else if (n == 4)
cout << "Winter";
else
cout << "Error"; //这一行根据需要调整
}
};
int main()
{
int n;
cin >> n;
Trans t(n);
t.trans();
return 0;
}
这也要用类啊。构造函数接收一个整数,然后增加一个输出函数就行了
#include <iostream>
using namespace std;
#include <string>
class Season
{
private:
int n;
public:
Season() {}
Season(int n) :n(n) {}
string GetSeason()
{
string s[4] = {"Spring","Summer","Fall","Winner"};
return s[n-1];
}
};
int main()
{
int n;
cin>>n;
Season s(n);
cout<<s.GetSeason();
}
定义个Season类,其私有变量为一个int型的number表示用户的输入,然后给了它一处理用户输入的函数。
#include <iostream>
using namespace std;
class Season {
private:
int number; // 用于保存用户输入的数字
public:
// 构造函数,初始化 number 值为 0
Season() {
number = 0;
}
// 处理用户输入的数字并输出相应的季节信息
void processInput() {
cout << "请输入一个整数(1-4)代表季节:" << endl;
cin >> number;
switch (number) {
case 1:
cout << "Spring" << endl;
break;
case 2:
cout << "Summer" << endl;
break;
case 3:
cout << "Fall" << endl;
break;
case 4:
cout << "Winter" << endl;
break;
default:
cout << "输入错误,请输入1-4中的整数!" << endl;
break;
}
}
};
int main() {
Season s; // 创建 Season 类的对象 s
s.processInput(); // 调用对象的 processInput 函数处理输入并输出结果
return 0;
}
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!#include<bits/stdc++.h>
using namespace std;
const int N = 3;//行列式的阶数
//按第一行展开计算|A|
double getA(double arcs[N][N],int n)
{
if(n==1)
{
return arcs[0][0];
}
double ans = 0;
double temp[N][N]={0.0};
int i,j,k;
for(i=0;i<n;i++)
{
for(j=0;j<n-1;j++)
{
for(k=0;k<n-1;k++)
{
temp[j][k] = arcs[j+1][(k>=i)?k+1:k];
}
}
double t = getA(temp,n-1);
if(i%2==0)
{
ans += arcs[0][i]*t;
}
else
{
ans -= arcs[0][i]*t;
}
}
return ans;
}
//计算每一行每一列的每个元素所对应的余子式,组成A*
void getAStart(double arcs[N][N],int n,double ans[N][N])
{
if(n==1)
{
ans[0][0] = 1;
return;
}
int i,j,k,t;
double temp[N][N];
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
for(k=0;k<n-1;k++)
{
for(t=0;t<n-1;t++)
{
temp[k][t] = arcs[k>=i?k+1:k][t>=j?t+1:t];
}
}
ans[j][i] = getA(temp,n-1);
if((i+j)%2 == 1)
{
ans[j][i] = - ans[j][i];
}
}
}
}
//得到给定矩阵src的逆矩阵保存到des中。
bool GetMatrixInverse(double src[N][N],int n,double des[N][N])
{
double flag=getA(src,n);
double t[N][N];
if(flag==0)
{
return false;
}
else
{
getAStart(src,n,t);
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
des[i][j]=t[i][j]/flag;
}
}
}
return true;
}
int main(){
double a[N][N];
double ans[N][N];
cout << " 请输入"<<N<<" 阶矩阵:"<<endl;
for(int i=0;i<N;i++)
for(int j=0;j<N;j++)
{
cin >> a[i][j];
}
GetMatrixInverse(a,N,ans);
cout<<" 该矩阵的逆为:"<<endl;
for(int i=0;i<N;i++)
{
for(int j=0;j<N;j++)
{
cout << ans[i][j]<<" ";
}
cout<<endl;
}
}