topic
Write a function to convert a binary integer (such as 10010) to a decimal integer and save it to a file output.txt
. In main()
calling the above function in the function n (1 to 10) times the number of calls by the random()
generating function.
Test site analysis
- Algorithm for converting binary to decimal
- File output stream
- Random number generation and range limitation
Code
#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;
}