一、目的和要求
1.了解C++格式化输出
2.熟悉基本数据类型、表达式与运算符
3.熟悉C++程序的流程控制
4.掌握函数的声明和调用
5.熟悉简单算法的实现
二、实验内容
- 编写程序将unsigned short整数转换为二进制数,并打印显示。
#include "stdafx.h"
#include <iostream>
#include <bitset>
using namespace std;
void Binary1(unsigned short n) {//递归
int a;
a = n % 2;
n = n >> 1;//右移除以2,左移乘以2
if (n == 0)
;
else
Binary1(n);
cout << a;
}
void Binary2(unsigned short n) {//利用bitset转换
cout << bitset<sizeof(int) * 8>(n) << endl;
}
int main()
{
unsigned short n;
cout << "请输入要转换的数字 :";
cin >> n;
cout << "利用递归转换 : ";
Binary1(n);
cout << "\n利用bitset转换 : ";
Binary2(n);
return 0;
}
运行结果:
2.定义:对于一个16位的无符号整数,称这个二进制数的前8位为“高位”,后8位为“低位”。要求写一程序将它的高低位交换。
例如:十进制数1234的二进制为:
00000100 11010010
交换高低位之后变为:
11010010 00000100
对应的十进制数是53764。
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
unsigned short n;
cout << "高低位交换\n请输入要转换的数字 :";
cin >> n;
cout << "转换前 : "<<n;
n = (n >> 8) | (n << 8);
cout << "\n转换后 : "<<n;
return 0;
}
运行结果:
3.编写程序求π的值。按以下公式计算:
其中arctan函数由下列形式的级数计算:
直到级数某项绝对值不大于10-15为止;π和x均为double型。
提示:首先实现arctan函数,然后在主程序中调用arctan函数计算π的值。
#include "pch.h"
#include <iostream>
using namespace std;
double arctan(double x) {
double a = x * x;
double b = x;
double r = 0;
int i = 1;
while (b / i > 1e-16) {
double c = b / i;
r = (i % 4 == 1) ? r + c : r - c;
b = b * a;
i += 2;
}
return r;
}
int main()
{
double pi = 16.0 * arctan(1 / 5.0) - 4.0 * arctan(1 / 239.0);
cout << "π=" << pi << endl;
system("pause");
return 0;
}
运行结果:
4.编写三个命名为MyMax的重载函数,分别实现求两整数、三个整数和两个浮点数最大值的功能。
#include "pch.h"
#include <iostream>
using namespace std;
int MyMax(int a, int b) {
if (a > b) {
return a;
}
else {
return b;
}
}
int MyMax(int a, int b, int c) {
return MyMax(a, MyMax(b, c));
}
double MyMax(double x, double y) {
if (x > y) {
return x;
}
else {
return y;
}
}
int main()
{
int a, b, c;
double x, y;
cout << "请输入两个要比较的整数 :";
cin >> a >> b;
cout << "最大值为 :" << MyMax(a, b) << endl;
cout << "\n请输入三个要比较的整数 :";
cin >> a >> b >> c;
cout << "最大值为 :" << MyMax(a, b, c) << endl;
cout << "\n请输入两个要比较的浮点数 :";
cin >> x >> y;
cout << "最大值为 :" << MyMax(x, y) << endl;
return 0;
}
运行结果: