顺序结构的程序设计

一、语句

简单语句

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;
} 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值