一、语句
简单语句
x = a+b;
t=a,a=b,b=t;
print(a,b);
符合语句
控制语句
#include <iostream>
using namespace std;
int main()
{
cout << "hello,world" << endl;
return 0;
}
二、输入与输出
C++语言的输入输出操作是用流对象(stream)实现的。若在程序中使用流对象cin和cout,应该将标准输入输出流库的头文件<iostream>包含到源文件中。
1. cout和cin对象的使用
#include <iostream>
using namespace std;
int main()
{
int c1, c2, c3;
cin >> c1 >> c2 >> c3;
cout << "c1=" << c1 << ", c2=" << c2 << ", c3=" << c3 << endl;
return 0;
}
cin输入时,为了分隔多项数据,默认要求在键盘输入数据之间使用空格、Tab键、回车作为分隔符。
2. 格式控制
可以在输入输出流中使用控制符进行格式控制。
使用这种方法,需要在程序中加入<iomanip>头文件。
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int a, m, n;
/* input: 144 46 -77 */
cin>>oct>>a>>hex>>m>>dec>>n;
/* output: 46 106 70 */
cout<<hex<<m<<' '<<oct<<m<<' '<<dec<<m<<endl;
/* output: 0x46 0106 70 */
cout<<showbase<<hex<<m<<' '<<oct<<m<<' '<<dec<<m<<endl;
/* 宽度为6,左对齐 */
cout<<left<<setw(6)<<n<<"end"<<endl;
/* 度为6,右对齐 */
cout.width(6);
cout<<right<<n<<"end"<<endl;
cout<<setw(10)<<77<<"end"<<endl;
cout<<setw(10)<<setfill('0')<<77<<"end"<<endl;
cout<<showpos<<1<<' '<<0<<' '<<-1<<endl;
cout<<noshowpos<<1<<' '<<0<<' '<<-1<<endl;
}
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double x,y,z,p,f;
float f1;
/* 3.14 3.14 3.14 3.14159 0.1 0.1e1 */
cin>>p>>f>>f1>>x>>y>>z;
cout<<"=====output====="<<endl;
cout<<p<<' '<<f<<' '<<f1<<' '<<x<<' '<<y<<' '<<z<<endl;
cout.precision(5);
cout<<p<<' '<<f<<' '<<f1<<' '<<x<<' '<<y<<' '<<z<<endl;
cout<<fixed<<p<<' '<<f<<' '<<f1<<' '<<x<<' '<<y<<' '<<z<<endl;
cout<<scientific<<p<<' '<<f<<' '<<f1<<' '<<x<<' '<<y<<' '<<z<<endl;
cout<<fixed<<setprecision(5)<<f<<"end"<<endl;
cout<<fixed<<setprecision(9)<<f<<"end"<<endl;
}
三、顺序结构
语句以其出现的顺序执行。
编程输入圆的半径,求圆的面积。
#include <iostream>
#include <iomanip>
using namespace std;
#define PI 3.1415926535
int main()
{
double r, area;
cin >> r;
area = PI*r*r;
cout << setprecision(10) << fixed << "area = " << area <<endl;
return 0;
}