C++基础知识实例解析(一)
今天小编和大家一起通过几个实例学习C++基础知识,下面进行实例解析: #include <iostream> using namespace std; int division(int x){ return x/2; } long division(long x){ return x/2; } float division(float x){ return x/2; } double division(double x){ return x/2; } int main() { int a; long b; float c; double d; cout<<"input a,b,c,d:"<<endl; cin>>a>>b>>c>>d; if(a!=0) cout<<a<<"/2="<<division(a)<<endl; else cout<<"input error!"<<endl; if(b!=0) cout<<b<<"/2="<<division(b)<<endl; else cout<<"input error!"<<endl; if(c!=0) cout<<c<<"/2="<<division(c)<<endl; else cout<<"input error!"<<endl; if(d!=0) cout<<d<<"/2="<<division(d)<<endl; else cout<<"input error!"<<endl; return 0; }
#include <iostream> using namespace std; void swap(int &a,int &b) { int t; t=a; a=b; b=t;} void max(int a,int b,int c,int &maxnum,int &minnum) { if(a<=b) swap(a,b); if(a<=c) swap(a,c); if(b<=c) swap(b,c); maxnum=a; minnum=c; } int main() { int a,maxnum,minnum; cout<<"input a,c:"; cin>>a>>b>>c; max(a,minnum); cout<<"maxnum="<<maxnum<<endl; cout<<"minnum="<<minnum<<endl; return 0; } 【总结】这个程序又两个被调函数,都用到引用。使用引用来一次返回两个参数值,方便简洁。 #include <iostream> using namespace std; float volumn(float a=10,float b=10,float c=10); int main() { float a,c; cout<<"没有实际参数值时,volumn="<<volumn()<<endl; cout<<"input a,c:"; cin>>a>>b>>c; cout<<"有实际参数值时,volumn="<<volumn(a,c)<<endl; return 0; } float volumn(float a,float b,float c) { return a*b*c; } 【总结】用带有默认参数值的函数需要注意的时,默认参数值只能在函数声明时标注,而在函数定义时则不能标注。当然,函数声明和函数定义标注在一起时不受这个限制。 #include <iostream> using namespace std; float avg(float,float); float avg(float,float,float); int main() { cout<<"The first student:"<<avg(80.0f,70.2f)<<endl; cout<<"The second student:"<<avg(80.1f,78.1f,12.3f)<<endl; cout<<"The third student:"<<avg(45.6f,90.1f,78.6f)<<endl; return 0; } float avg(float x,float y) { return (x+y)/2.0; } float avg(float a,float c) { return (a+b+c)/3; } float avg(float a,float c,float d){ return (a+b+c+d)/4; } 【分析】这几个avg函数重载的出发点是由于其形参个数不同。并且由于函数体只有一句话,并且没有选择和循环等复杂结构,故也可以将其定义为内联函数,以提高程序运行效果。 以上就是今天小编跟大家分享的C++经典实例,需要大家亲自动手操作才能领会C++语言带给我们的乐趣。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |