微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

《数据结构》实验一:VC编程环境灵活应用

1. 设计一个单文件结构程序完成从键盘输入两个数,输出二者的“和”和“积”的结果。

#include <iostream>  
using namespace std;  
void he(int a,int s)  
{  
    int m;  
    m=a+s;  
    cout<<"两个数的和为:"<<m<<endl;  
}  
void he(double d,double f)  
{  
    double n;  
    n=d+f;  
    cout<<"两个数的和为:"<<n<<endl;  
}  
void ji(int g,int h)  
{  
    int b;  
    b=g*h;  
    cout<<"两个数的积为:"<<b<<endl;  
}  
void ji(double j,double k)  
{  
    double v;  
    v=j*k;  
    cout<<"两个数的积为:"<<v<<endl;  
}  
  
int main()  
{  
        float q,w;  
    cout<<"输入两个数:";  
        cin>>q>>w;  
        he(q,w);  
    ji(q,w);  
    cout<<endl;  
    return 0;  
}  


2.使用函数的模板来实现上述功能。

#include <iostream>  
using namespace std;  
template<class T1,class T2>  
T1 he(T1 a,T2 s)  
{  
    T1 d;  
    d=a+s;  
    cout<<"两个数的和为:"<<d<<endl;  
    return d;  
}  
  
template<class Y1,class Y2>  
Y1 ji(Y1 q,Y2 w)  
{  
    Y1 e;  
    e=q*w;  
    cout<<"两个数的积为:"<<e<<endl;  
   return e;  
}  
  
int main()  
{  
    float z,x;  
    cout<<"输入两个数:";  
    cin>>z>>x;  
    he(z,x);  
    ji(z,x);  
    return 0;  
}  


3.使用一个类来实现上述功能。

#include <iostream>  
using namespace std;  
  
template <typename T>  
  class tem  
{  
    public:  
        int he(int x,int y)  
        {  
        int r;  
        r=x+y;  
            cout<<"两个数的和为:"<<r<<endl;  
        return r;
		}  
  
        int ji(int x,int y)  
        {  
        int v;  
        v=x*y;  
        cout<<"两个数的积为:"<<v<<endl; 
		return v;
        }  
};  
  
int main()  
{  
    int a,b;  
    cout<<"输入两个数:";  
    cin>>a>>b; 
	tem<int>o;
    o.he(a,b);  
    o.ji(a,b);  
    return 0;  
}  


 

PS.老师类模板那个只会做整数。。。不知道怎么写。。。好像模板也有些错误。。。

调试结果:

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐