Convert a binary integer to a decimal integer, save it to a file, and call randomly

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

  1. Algorithm for converting binary to decimal
  2. File output stream
  3. 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;
}

Guess you like

Origin www.cnblogs.com/Za-Ya-Hoo/p/12680517.html