物联1131-23
实验内容:
1. 设计一个单文件结构程序完成从键盘输入两个数,输出二者的“和”和“积”的结果。要求如下:
1)设计函数来计算“和”和“积”,在主函数中调用,并能考虑重载函数,使整数和小数均能计算。
2)分别使用单步调试和断点调试来调试程序。并多次运行力求熟练调试方法。
#include<iostream>
using namespace std;
int sum(int i,int j)
{
return i+j;
}
double sum(double i,double j)
{
return i+j;
}
int multiply(int i,int j)
{
return i*j;
}
double multiply(double i,double j)
{
return i*j;
}
double main()
{ double a,b,c,d;
cout<<"please input two numbers."<<endl;
cin>>a>>b;
c=sum(a,b);
d=multiply(a,b);
cout<<a<<"+"<<b<<"="<<c<<endl;
cout<<a<<"*"<<b<<"="<<d<<endl;
return 0;
}
2.使用函数的模板来实现上述功能。
#include<iostream>
using namespace std;
template<class T>
T sum(T a, T b)
{
returna+b;
}
template<typename T>
T multiply(T a,T b)
{
returna*b;
}
int main()
{
double a,b,c,d;
cout<<"please input two numbers."<<endl;
cin>>a>>b;
c= sum(a,b);
d=multiply(a,b);
cout<<a<<"+"<<b<<"="<<c<<endl;
cout<<a<<"*"<<b<<"="<<d<<endl;
return 0;
}
3.使用一个类来实现上述功能。要求:
1)使用类模板
2)使用多文件:类的声明有头文件中;类的函数定义一个源文件中,在主程序文件中设计主函数程序,在实例化输出结果。
头文件
#ifndef __EXP_H__
#define __EXP_H__
#include<iostream>
template<class A,class B>
class sum
{
public:
sum(A a,B b);
};
template<class A,class B>
sum<A,B>::sum(A a,B b)
{
cout<<a<<"+"<<b<<"="<<a+b<<endl;
}
#endif
所有程序
#include<iostream>
using namespace std;
template<class A,class B>
class sum
{
public:
sum(A a,B b);
};
template<class A,class B>
sum<A,B>::sum(A a,B b)
{
cout<<a<<"+"<<b<<"="<<a+b<<endl;
}
double main()
{
inti=3,j=5;
doublea=5.6,b=15.3;
sum<int,int>(i,j);
sum<double,double>(a,b);
return0;
}