题目
编写函数,将一个二进制整数(如:10010)转换为十进制整数,保存到文件output.txt
中。在 main()
函数中调用上面的函数 n(1 ~ 10)次,调用次数由random()
函数生成。
考点分析
- 二进制转化为十进制的算法
- 文件输出流
- 随机数的生成和范围限定
代码
#include<iostream>
#include<fstream>
#include<ctime>
using namespace std;
int power2(int n) {
int res = 1;
for (int i = 0; i < n; i++)
res *= 2;
return res;
}
ofstream of("outputFile.txt"); //要设置全局变量,要是设置在函数里,每次都会覆盖上一次的输出文件
void output(int n) {
int dec = 0;
for (int i = 0; n != 0; i++) {
int temp = n % 10;
n /= 10;
dec += temp * power2(i);
}
of << dec << endl;
}
int main() {
srand((unsigned)time(0)); //种子
int times = (rand() % 10) + 1; //随机生成调用次数
int n;
for (int i = 0; i < times; i++) {
cin >> n;
output(n);
}
return 0;
}