实验一:C++对C的扩充

实验目的:
(1)了解在面向过程程序设计中C++对C功能的扩充与增强,并善于在编写程序过程中应用这些新的功能。
(2)进一步熟悉在所用的系统上编辑、编译、连接和运行C++程序的方法。
(3)进一步熟悉C++程序的结构和编程方法。

实验内容:
(1)输入以下程序,进行编译,观察编译情况,如果有错误,请修改程序,再进行编译,直到没有错误,然后进行连接和运行,分析运行结果(本题是《C++面向对象程序设计》第1章习题第9题)。

# include <iostream>
using namespace std ; 
int main ( )
{ int a , b ; 
c = add ( a , b ) 
cout <<" a + b = " <<c<<endl ; 
return 0 ;
} 
int add ( int x , int y ) ; 
{ z = x + y ; 
return (z);
}


正确代码如下:

#include<iostream>
using namespace std;
int main()
{
	int a,b,c;
	int add(int a,int b);
	cin>>a>>b;
	c=add(a,b);
	cout<<"a+b="<<c<<endl;
	return 0;
}
int add( int x,  int y)
{
	int z;
	z=x+y;
	return(z);
}

(2)编一个程序,用来求2个或3个正整数中的最大数。
① 用不带默认参数的函数实现。
② 用带有默认参数的函数实现。
(本题是《C++面向对象程序设计》第1章习题第11题)
在此贴上带默认参数的函数:

#include<iostream>
using namespace std;

int main()
{
	int a,b,c;
	cin>>a>>b>>c;
	int max(int x,int y,int z=0);
	cout<<"max3="<<max(a,b,c)<<endl;
	cout<<"max2="<<max(a,b)<<endl;
	return 0;
	
}
int max(int x,int y,int z)
{
	if (x<y)  x=y;
	if (x<z)  x=z;
	return x;
}

(3)输入两个整数,将它们按由大到小的顺序输出(本题是《C++面向对象程序设
计》第1章习题第12题)。
① 使用指针方法。
② 使用变量的引用。
1.指针方法:

#include<iostream>
using namespace std;
int main()
{
	int a,b;
	cin>>a>>b;
	void sort(int *x,int *y);
	sort(&a,&b);

}

void sort(int *x,int *y)
{
	if(*x>=*y)
	cout<<*x<<">="<<*y<<endl;
	else
	cout<<*y<<">="<<*x<<endl;
}

2.变量的引用:

#include<iostream>
using namespace std;
int main()
{
	int a,b;
	int &x=a,&y=b;
	cin>>a>>b;
	void sort(int x,int y);
	sort(a,b);
	
}

void sort(int x,int y)
{
	if(x>=y)
	cout<<x<<">="<<y<<endl;
	else
	cout<<y<<">="<<x<<endl;
}

(4)对3个变量按由小到大顺序排序,要求使用变量的引用(本题是《C++面向对象程序设计》第1章习题第13题)。

#include<iostream>
using namespace std;

void sort(int &a,int &b,int &c);
void exchange(int &a,int &b);
int main()
{
	int x,y,z;
	cin>>x>>y>>z;
	sort(x,y,z);
	cout<<x<<" "<<y<<" "<<z<<endl;
	
}

void sort(int &a,int &b,int &c)
{
	if(a>b) exchange(a,b);
	if(a>c) exchange(a,c);
	if(b>c) exchange(b,c);
}
void exchange(int &a,int &b)
{
	int temp;
	temp=a;
	a=b;
	b=temp;
}

(5)有5个字符串,要求对它们按由小到大顺序排列,用string方法(本题是《C++ 面向对象程序设计》第1章习题第16题)。

#include<iostream>
#include<string>
using namespace std;

void sort(string s[]);
int main()
{
	string s[5];
	int i;
	for(i=0;i<5;i++)
	{
		cin>>s[i];
	}
	sort(s);
	for(i=0;i<5;i++)
	{
		cout<<s[i]<<endl;
	}
	return 0;
	
}
void sort(string s[])
{
	int i,j;
	string temp;
	for(i=0;i<4;i++)
	{
		for(j=0;j<4-i;j++)
		{
			if(s[j]>s[j+1])
			{
				temp=s[j];
				s[j]=s[j+1];
				s[j+1]=temp;
			}
		}
	}
}

(6)编一个程序,用同一个函数名对n个数据进行从小到大排序,数据类型可以是整型、单精度型、双精度型(本题是《C++面向对象程序设计》第1章习题第17题和18题)。
① 用重载函数实现。
② 用函数模板实现。
奈何本人太菜,在此贴出一位大佬的解答 用重载函数实现排序

  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值