#include <iostream>
using namespace std;
int main(){
int a,b,c,MAX;
cout<<"please enter three number";
cin>>a>>b>>c;
MAX=a?b:a,b;
MAX=MAX?c:MAX,c;
cout<<"big number is"<<MAX;
return 0;
}
int &changevalue()
{
static int a_return =-29;
return a_return;
}
int main()
{
int &a_return=changevalue();
a_return =20;
cout<<changevalue()<<endl;
system("pause");
}
2647cpp-examples-largest-number-among-three
也可以使用三元运算符,更为简单:
#include <iostream> using namespace std; int main(){ int a,b,c,MAX; cout<<"please enter three number"; cin>>a>>b>>c; MAX=a?b:a,b; MAX=MAX?c:MAX,c; cout<<"big number is"<<MAX; return 0; }2646cpp-examples-largest-number-among-three
可以使用临时变量记录最大值:
#include <iostream> using namespace std; int main() { float n1, n2, n3, max; cout << "请输入三个数: "; cin >> n1 >> n2 >> n3; if(n1 >= n2) { max = n1; }else{ max = n2; } if(n3 >= max) { max = n3; } cout << "最大数为: " << max; return 0; }2645cpp-examples-even-odd
可以用与运算判断:
#include <iostream> using namespace std; int main() { int n = 1; cout << "输入一个整数: "; cin >> n; if ( ( n & 1 ) == 0) cout << n << " 为偶数。"; else cout << n << " 为奇数。"; return 0; }2644cpp-constructor-destructor
改进了下上面的列子:
#include<iostream> using namespace std; class Student1 { public: int a=0; int b=0; void fprint() { cout << " a = " << a << " " << "b = " << b << "\n"<<endl; } Student1() { cout << "无参构造函数Student1" << endl; } Student1(int i):a(i),b(a) { cout << "有参参构造函数Student1" << endl; } Student1(const Student1& t1) { cout << "拷贝构造函数Student1" << endl; this->a = t1.a; this->b = t1.b; } Student1& operator = (const Student1& t1) // 重载赋值运算符 { cout << "赋值函数Student1" << endl; this->a = t1.a; this->b = t1.b; return *this; } }; class Student2 { public: Student1 test; Student2(Student1& t1) { t1.fprint(); cout << "D: "; test = t1; } // Student2(Student1 &t1):test(t1){} }; int main() { cout << "A: "; Student1 A; A.fprint(); cout << "B: "; Student1 B(2); B.fprint(); cout << "C: "; Student1 C(B); C.fprint(); cout << "D: "; Student2 D(C); D.test.fprint(); }2643returning-values-by-reference
教程里面举的例子可能不太好理解,下面是我写的一个例子:
int &changevalue() { static int a_return =-29; return a_return; } int main() { int &a_return=changevalue(); a_return =20; cout<<changevalue()<<endl; system("pause"); }最终,屏幕上打印的结果是:20