第三章
一、单项选择题
1. 声明abc的函数原型,该函数返回double型数据,需要传递一个double型和一个char型参数的。
2.inline
3.对象、对象指针、引用
4.函数func返回字符型引用,并且需要传递一个char型和一个int型参数。
5.int *fun(char,int&);
二、单项选择题
1.A;使用了const限制改变。
2.C;函数重载的参数个数和数据类型可相同也可以不相同,返回值也可相同可不相同。只
是函数重载的依据是参数个数和数据类型的不同。
3.C;参考课本P61,当形参有两个时,使用C的格式。
三、改错题
1.下面程序错在何处?
template <class T>
T fun(T x)
{
T y;
y = x*x - T; // 错误,T是类型,不是变量,不能参加运算;
return y;
}
2.找出下面程序中的错误之并改正之。
#include <iostream.h> //C++标准中没有iostream.h头文件
template <class Type>
Type max(T x, y) // x的类型和template中的不一样,并且y没有类型。
{
return (x>y) ? (x) : (y);
}
修改如下:
#include <iostream>
邗沟
template <class Type>
Type max(超级演说家第四季Type x, Type y)
{
return (x>y) ? (x) : (y);
}
3. 找出下面程序中的错误之并改正之。
函数change 的参数定义成了常量,只能使用参数,而无权修改他。
#include <iostream>
#include <string>
using namespace std;
void change(const string& s)
//函数change 的参数定义成了常量,只能使用参数,而无权修改他。
{
s = s + "pig!";
}
void main()
{
string str("it is a ");
爱国的手抄报
change(str);
cout << str << endl;
}
修改如下:
#include <iostream>
#include <string>
using namespace std;
void change(string& s)
//函数change 的参数定义成了常量,只能使用参数,而无权修改他。
{
s = s + "pig!";
}
void main()
{
string str("it is a ");
change(str);
cout << str << endl;
}
四、编程题
1.编写一个求方程ax2 + bx + c = 0的根 的程序,用3个函数分别求当b2-4ac大于零、等于零、和小于零时的方程的根。要求从主函数输入a,b,c的值并输出结果。
#include <iostream>
#include <cmath> //使用数学求根函数sqrt(),需要包含头文件cmath
using namespace std;
void equation_1 (int a, int b, int c)
{
double x1, x2, temp;
temp = b*b - 4 * a * c;
x1 = (-b + sqrt(temp) ) / (2 * a * 1.0);
//分母乘以1.0是为了保证分母的结果位double型
x2 = (-b - sqrt(temp) ) / (2 * a * 1.0);
cout<<"两个不相等的实根"<< endl;
cout<<"x1 = "<< x1<<", x2 = "<< x2<< endl;
}
void equation_2 (int a, int b, int c)
{
double x1, x2, temp;
temp = b*b - 4 * a * c;
x1 = (-b + sqrt(temp) ) / (2 * a * 1.0);
x2 = x1;
cout<<"两个相等的实根"<< endl;
cout<<"x1 = "<< x1<<", x2 = "<< x2<< endl;
}楷体字怎么练
void equation_3 (int a, int b, int c)
{
double temp, real1, real2, image1, image2;
temp = - (b*b - 4 * a * c);
real1 = -b / (2 * a *1.0);
real2 = real1;
image1 = sqrt(temp);
image2 = - image1;
cout<<"两个虚根"<< endl;
cout<<"x1 = "<< real1<<" + "<< image1<<"j"<< endl;
cout<<"x2 = "<< real2<<" - "<< -image2<<"j"<< endl;
//加了两个减号,显示更清晰
内在驱动力
}
void main()
{
int a, b, c;
double temp;
cout<<"输入a,b,c的值"<< endl; //从主函数输入a、b、c
cin>>a>>b>>c;
cout<<"社会实践情况方程为:"<< a<<"x*x+"<< b<<"x+"<< c<<" = 0"<< endl;
qq个签 temp = b*b - 4 * a * c;
if(temp > 0) //一年级上册语文课件使用if选择语句进行判断选择
equation_1 (a, b, c);
if(temp == 0)
equation_2 (a, b, c);
if(temp < 0)
equation_3 (a, b, c);
}
运行结果:
2.定义函数up(ch),如字符变量ch是小写字母就转换成大写字母并通过up返回,否则字符ch不改变。要求在短小而完全的程序中显示这个程序是怎样被调用的。
#include < iostream >
#include < string >