(一)C++基础入门

一、目的和要求

1.了解C++格式化输出
2.熟悉基本数据类型、表达式与运算符
3.熟悉C++程序的流程控制
4.掌握函数的声明和调用
5.熟悉简单算法的实现

二、实验内容

  1. 编写程序将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;
}

运行结果:
在这里插入图片描述

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值