2010年
1、输入 n 个十进制数转换成二进制写到文件,n 是随机得到的
考虑到对于负数的二进制表示有补码、反码等,所以这里默认输入的整数都是正数。将十进制转换为二进制字符串的功能是通过自定义函数完成的。
下面是具体代码:
//2010_1:输入 n 个十进制数转换成二进制写到文件,n 是随机得到
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
//10进制转2进制字符串的函数,没有考虑负数情况
string toBinary(int d){
string s;
if (d == 0)
return "0";
while (d){
s += (d%2 > 0) ? "1":"0";
d = d/2;
}
reverse(s.begin(), s.end()); //字符串逆置
return s;
}
int main(){
ofstream os("/Users/.../BinaryNumber.txt");
if (!os) {
cerr << "File cannot be opened!\n";
exit(EXIT_FAILURE);
}
int n;
cout << "Enter the n:\n";
cin >> n;
int decimal;
while (n > 0) {
cout << "Please enter a decimal number:\n";
cin >> decimal;
os << toBinary(decimal) << endl; //写入文件
n--;
}
return 0;
}
测试结果如下图所示:
2、写两个模板函数:插入排序法的迭代实现与递归实现
模版不是关键,主要是如何实现插入排序法。
其中递归的实现我参考了
http://blog.csdn.net/u014309268/article/details/39691205这篇文章。
下面上代码:
//2010_2:写两个模板函数:插入排序法的迭代实现与递归实现
#include <iostream>
using namespace std;
/*********** 插入排序法的迭代实现 ***********/
template <class T1>
void InsertSort_1(T1 a[],int n){
T1 temp;
int j;
for (int i = 1; i < n; i++) {
temp = a[i]; //把未排序数组的第一个元素赋给temp
j = i - 1;
//通过while循环把比temp大的数组元素向后移一格
while (j >= 0 && temp < a[j]) {
a[j+1] = a[j];
j--;
}
a[j+1] = temp; //把temp放回合适的位置
}
}
/****************************************/
/*********** 插入排序法的递归实现 ***********/
template <class T2>
void Insert(T2 b[],int n)
{
int i = n-1;
T2 temp = b[n];
while(i >= 0 && temp < b[i])
{
b[i+1] = b[i];
i--;
}
b[i+1] = temp;
}
template <class T2>
void InsertSort_2(T2 b[],int n)
{
if(n > 0)
{
InsertSort_2(b,n-1); //递归表示前面已经排序好
Insert(b,n);
}
else //递归的出口是n=0
return ;
}
/****************************************/
int main(){
int A[7] = {
2,3,4,1,5,12,11};
double B[10] = {
3.4,1.1,9.9,0.3,0.2,5.4,5.3,5.5,123,3.39};
InsertSort_1(A,sizeof(A) / sizeof(*A));
InsertSort_2(B,sizeof(B) / sizeof(*B) - 1); //递归的第二个参数的含义是数组末尾下标
for (auto const item : A) //尝试使用C++11新特性:基于范围的for语句
cout << item << " ";
cout << endl;
for (auto const item : B)
cout << item << " ";
cout << endl;
return 0;
}
运行结果就不贴出了,就是两个排好序的数组。