1、下面程序错在何处? template <class T> T fun(T x){ T y; y=x*x-T; return y; } 是不是这个T没用对?y=x*x-T; 2、找出下面程序中的错误并改正 #include <iostream.h> template <class Type> Type max(T x,y) {return (x>y)?(x):(y);} Type max(T x,y)改成Type max(T x,Ty)3、找出下面程序中的错误并改正 void change(const string&s) {s=s+"png!";} { void main(){ string str("it is a"); change(str); } {s=s+"png!";} 改成{string s=s+"png!";}
四、 2、定义函数up(ch),如字符变量ch是小写字母就转换成大写字母并通过up返回,否则字符ch不改变。要求在短小而完全的程序中显示这个程序是怎样被调用的。 #include <iostream> using namespace std; char up (char ch) { if(up>'a'&&up<'z';) {ch-=32} return up; }
6题:#include <iostream> #include <math.h> #include <string>using namespace std;template <typename T>T sum(T array[],int n) { T sum = 0; for(int i = 0; i < n; i ++) { sum += array[i]; } return sum; }int main() { int arr[] = {1,2,3,4}; cout << sum(arr,4) << endl; }
刚才那个是第七题,这个是第六题:交换排序#include <iostream> #include <math.h> #include <string>using namespace std; /*** 用函数模板实现3个数值中按最小值到最大值排序的程序 **/ template <typename T>void sort(T x,T y,T z) { T m; if(x > y) { m = x; x = y; y = m; } if(x > z) { m = x; x = z; z = m; } if(y > z) { m = y; y = z; z = m; } cout << x << "," << y << "," << z << endl; } int main() { sort(1,5,0); sort(2.2,1.1,3.3); }
template <class T>
T fun(T x){
T y;
y=x*x-T;
return y;
}
是不是这个T没用对?y=x*x-T;
2、找出下面程序中的错误并改正
#include <iostream.h>
template <class Type>
Type max(T x,y)
{return (x>y)?(x):(y);} Type max(T x,y)改成Type max(T x,Ty)3、找出下面程序中的错误并改正
void change(const string&s)
{s=s+"png!";}
{
void main(){
string str("it is a");
change(str);
} {s=s+"png!";} 改成{string s=s+"png!";}
2、定义函数up(ch),如字符变量ch是小写字母就转换成大写字母并通过up返回,否则字符ch不改变。要求在短小而完全的程序中显示这个程序是怎样被调用的。
#include <iostream>
using namespace std;
char up (char ch)
{
if(up>'a'&&up<'z';)
{ch-=32}
return up;
}
#include <math.h>
#include <string>using namespace std;template <typename T>T sum(T array[],int n)
{
T sum = 0;
for(int i = 0; i < n; i ++)
{
sum += array[i];
}
return sum;
}int main()
{
int arr[] = {1,2,3,4};
cout << sum(arr,4) << endl;
}
#include <math.h>
#include <string>using namespace std;
/***
用函数模板实现3个数值中按最小值到最大值排序的程序
**/
template <typename T>void sort(T x,T y,T z)
{
T m;
if(x > y)
{
m = x;
x = y;
y = m;
}
if(x > z)
{
m = x;
x = z;
z = m;
}
if(y > z)
{
m = y;
y = z;
z = m;
}
cout << x << "," << y << "," << z << endl;
}
int main()
{
sort(1,5,0);
sort(2.2,1.1,3.3);
}
#include <math.h>
#include <string>using namespace std;
/***
宝义函数up(ch),如字符变量ch是小写字母就转换成大写字母并通过up返回,
否则字符ch不改变。要求在短小而完全的程序中显示这个程序是怎样被调用的。
**/char up(char);
int main()
{
char c;
cout << "Input a char:";
cin.get(c);
cout << up(c) << endl;
}char up(char c)
{
if(c >= 'a' && c <= 'z')
{
return c - 32;
}
return c;
}