1.基本的输入输出,使用cin>>输入输入、使用cout<<输出
#include<iostream> using namespace std; int main() { int a,b,d,min; cout<<"Enter two numbers:"<<endl; cin>>a>>b; cout<<"min = "<<(min=a>b? b:a); for(d=2;d<min;d++) if(((a%d)==0) && ((b%d)==0)) break; if (d==min) { cout<<"no common denominators"<<endl; return 0; } cout<<"the lowest common denominator is"<<d<<endl; return 0; }
Enter two numbers: 1 2 min = 1 the lowest common denominator is2 Program ended with exit code: 0
2.使用引用,引用用地址符号&表示,引用就是给变量或者常量起的另一个别名,操作的还是同一个数据
//引用当做返回值
/* 需求:使用引用返回函数值 */ #include<iostream> using namespace std; int &f(int &i) //定义函数返回一个整数类型的引用,等价于返回数值i { i+=10; return i; } int main() { int k=0; int &m=f(k); //k=i=10 cout<<k<<endl; m=20; cout<<k<<endl; return 0; }
10 20 Program ended with exit code: 0
//引用当做参数
/* 需求:引用作为函数参数 */ #include<iostream> using namespace std; void f(int &m,int n) { int temp; temp = m; m = n; n =temp; } int main() { int a = 5,b = 10; cout<<"a = "<<a<<" "<<"b = "<<b<<endl; f(a,b); cout<<"a = "<<a<<" "<<"b = "<<b<<endl; return 0; }
a = 5 b = 10 a = 10 b = 10 Program ended with exit code: 0
3.使用作用域运算符::,作用变量或常量或函数的有效区域
/* 需求:作用域运算符:: */ #include<iostream> using namespace std; int i=15; int main () { int i; i = 100; ::i = i+1; cout<<i<<endl; cout<<::i<<endl; return 0; }
100 101 Program ended with exit code: 0
4.结构体的简单使用,它有自己的属性成员和方法成员,需要创建结构体成员变量才能调用自己的属性和方法
//#include<iostream> //#include<cmath> //using namespace std; #include<iostream.h> #include<math.h> struct Complex //声明一个名为Complex的结构体 { double real; //数据成员,复数的实部 double imag; //数据成员,复数的虚部 void init(double r,double i) //成员函数init,给real和imag赋给初值 { real = r; imag = i; } double abscomplex() //成员函数,求复数的绝对值 { double t; t = real*real+imag*imag; return sqrt(t); } }; int main() { Complex A; //定义结构体Complex的成员变量A A.init(1.1,2.2); //调用成员函数init,给real和imag赋给初值 cout<<"复数的绝对值是:"<<A.abscomplex()<<endl; //调用成员函数abscomplex return 0; }
复数的绝对值是:2.45967 Program ended with exit code: 0
程序猿神奇的手,每时每刻,这双手都在改变着世界的交互方式!