现在的位置: 首页 > 综合 > 正文

预处理宏与移位运算符

2013年03月06日 ⁄ 综合 ⁄ 共 1806字 ⁄ 字号 评论关闭
//:预处理宏.cpp
//Mathematical operators
#include<iostream>
using namespace std;

//A macro to display a string and a value

#define PRINT(STR, VAR) \
	cout << STR " = " << VAR << endl;	//cout语句中,两个紧紧相邻的引号默认合并

int main()
{
	int i, j, k;
	cout << "Enter an integer: ";
	cin >> j;
	cout << "Enter another integer: ";
	cin >> k;
	PRINT("j", j);	PRINT("k", k);
	i = j + k;	PRINT("j + k", i);
	i = j - k;  PRINT("j - k", i);
	i = j / k;  PRINT("k / j", i);
	i = j * k;  PRINT("k * j", i);
	i = j % k;  PRINT("k % j", i);
	//The following only works with integers:
	j %= k;	PRINT("j %= k", j);
	float u, v, w;	//Applies to doubles, too
	cout << "Enter a floating_point number: ";
	cin >> v;
	cout << "Enter another floating_point number: ";
	cin >> w;
	PRINT("v", v);	PRINT("w", w);
	u = v + w;	PRINT("v + w", u);
	u = v - w;	PRINT("v - w", u);
	u = v * w;	PRINT("v * w", u);
	u = v / w;	PRINT("v / w", u);
	//The following works for ints, chars
	//and doubles too:
	PRINT("u", u);	PRINT("v", v);
	u += v;	PRINT("v += v", u);
	u -= v;	PRINT("v -= v", u);
	u *= v;	PRINT("v *= v", u);
	u /= v;	PRINT("v /= v", u);
	return 0;
}///:~


/*

  Enter an integer: 2
Enter another integer: 1
j = 2
k = 1
j + k = 3
j - k = 1
k / j = 2
k * j = 2
k % j = 0
j %= k = 0
Enter a floating_point number: 3.2
Enter another floating_point number: 1.6
v = 3.2
w = 1.6
v + w = 4.8
v - w = 1.6
v * w = 5.12
v / w = 2
u = 2
v = 3.2
v += v = 5.2
v -= v = 2
v *= v = 6.4
v /= v = 2
Press any key to continue

  */

//:移位运算符.cpp
//{L} printBinary
//Demonstration of bit manipulation
#include<iostream>
using namespace std;

//:printBinary
//Display a byte in binary
void printBinary(const unsigned char val)
{
	for(int i = 7; i >= 0; --i)
		if(val & (1 << i))
			cout << "1";
		else
			cout << "0";
}///:~

#define PR(STR, EXPR) \
cout << STR; printBinary(EXPR); cout << endl;

int main()
{
	unsigned int getval;
	unsigned char a, b;
	cout << "Enter a number between 0 and 255: ";
	cin >> getval; a = getval;
	cout  << a << endl;
	PR("a in binary: ", a);
	cout << "Enter a number between 0 and 255: ";
	cin >> getval;  b = getval;
	PR("b in binary: ", b);
	PR("a | b = ", a | b);
	PR("a & b = ", a & b);
	PR("a ^ b = ", a ^ b);
	PR("~a = ", ~a);
	PR("~b = ", ~b);
	//An interesting bit pattern:
	unsigned char c = 0x5A;
	PR("c in binary: ", c);
	a |= c;
	PR("a |= c; a = ", a);
	b &= c;
	PR("b &= c; b = ", b);
	b ^= a;
	PR("b ^= a; b = ", b);
	return 0;
}///:~

抱歉!评论已关闭.