《c++语言程序设计》第二章 代码篇

本文展示了C++中变量的使用,包括常量与变量的赋值,如PI的赋值;递增运算符的两种用法,如`a++`和`++a`的差异;循环结构的运用,如for和while,以及do...while循环;交换变量值的方法;基本数据类型的大小(sizeof);以及ASCII码的打印。同时,还涵盖了算术运算和程序的输出。
摘要由CSDN通过智能技术生成
//2-4
int main()
{
	const float PI = 3.1416;
	float a;
	a = PI;
	cout << a;
    return 0;
}
//2-9
int main()
{
	int a = 30;
	int b = a++;
	int c = ++a;
	cout << a << endl;
	cout << b << endl;
	cout << c << endl;
	return 0;
}

执行完以上语句后,a的值为32,b的值为30,c的值为32。运行截图如下:

//2-11
int main()
{
	int n;
	for (n = 0; n < 100; n++);
	cout << n;
	return 0;
}

 for循环执行条件为n<100,故满足情况时,最后n为99,之后再执行n++,因此n的最终值为100。

//2-12
//使用while语句
int main()
{
	int n = 100;
	while (n < 200)
	{
		n = n + 2;
		cout << n << " ";
	}
	return 0;
}
//2-12
//使用do...while语句
int main()
{
	int n = 100;
	do {
		n = n + 2;
		cout << n << " ";
	} while (n < 200);
	return 0;
}

 运行截图如下:

//2-14
int main()
{
	int x, y;
	cout << "请输入两个不相等的整数x和y:"<<endl;
	cin >> x >> y;
	if (x < y)
	{
		y = x;
	}
	else {
		x = y;
	}
	cout << "x=" << x << endl;
	cout << "y=" << y << endl;
}
//2-15
int main()
{
	int i;
	int j;
	i = 10;
	j = 20;
	cout << "i+j=" << (i + j);
	return 0;
}

输出结果为:i+j=30

//2-16
int main()
{
	double a;
	cout << "请输入一个数:" ;
	cin >> a;
	cout << "您输入的数为:" << a;
	return 0;
}

 例如:

//2-17
int main()
{
	cout << sizeof(char) << endl;
	cout << sizeof(short) << endl;
	cout << sizeof(int) << endl;
	cout << sizeof(long) << endl;
	cout << sizeof(long long) << endl;
	cout << sizeof(double) << endl;
	cout << sizeof(float) << endl;
}

 

//2-18
int main()
{
	char a;
	for (a = 32; a < 127; a++)
	{
		cout << a << " ";
	}
	return 0;
}

运行截图如下:

//2-19
int main()
{
	unsigned int x;
	unsigned int y = 100;
	unsigned int z = 50;
	x = y - z;
	cout << "Difference is:" << x << endl;
	x = z - y;
	cout << "\nNow difference is:" << x << endl;
	return 0;
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值