@latevko

Как считать из файла двоичные числа величиной максимум 8 бит и записать в массив?

Нужно написать программу, которая обнаруживает 2 наименьших (минимум) и 2 наибольших (максимальных) элемента из одномерного массива из десяти чисел, введенных в двоичном коде (макс. 8 бит), который программа считывает из файла. Он печатает все числа на экране вместе с их транскрипцией в десятичной системе, включая минимумы и максимумы.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 89
#define Z 10

void qs(long int *s_arr, int first, int last);
int dec2bin(int num);

int main()
{
    // variables
    char binArr[N];
    char *end;
    char ch = 0;
    long int decArr[Z];

    // opening a file and reading from it
    FILE *f = fopen("01.txt", "rb");
    while (!feof(f))
    {
        
        fgets(binArr, N, f);
    }
    printf("%s\n", binArr);
    printf("---------------------------------\n");
    fclose(f);
    // decimal conversion

    decArr[0] = strtol(binArr, &end, 2);
    for (int i = 1; i < 10; i++)
    {
        decArr[i] = strtol(end, &end, 2);
    }
    // output binary numbers in decimal format
    for (int i = 0; i < 10; i++)
    {
        printf("#%d - %d = %ld\n", i + 1, dec2bin(decArr[i]), decArr[i]);
    }
    // sorting an array
    qs(decArr, 0, Z - 1);
    // max and min output
    printf("max#1= %d = %ld\n", dec2bin(decArr[Z - 1]), decArr[Z - 1]);
    printf("max#2= %d = %ld\n", dec2bin(decArr[Z - 2]), decArr[Z - 2]);
    printf("min#1= %d = %ld\n", dec2bin(decArr[0]), decArr[0]);
    printf("min#2= %d = %ld\n", dec2bin(decArr[1]), decArr[1]);
}

int dec2bin(int num)
{
    int bin = 0, k = 1;

    while (num)
    {
        bin += (num % 2) * k;
        k *= 10;
        num /= 2;
    }

    return bin;
}

void qs(long int *s_arr, int first, int last)
{
    if (first < last)
    {

        // the pivot element of the array is selected (l + r) / 2
        int left = first, right = last, middle = s_arr[(left + right) / 2];
        do
        {
            // splits into 2 elements which are <= and> = to the pivot element of the array

            // two variables store the indices of the sorted chunk on the left side increases by 1 from the right side decreases by 1 to the middle of the array
            // we move them to the meeting, that is, left ++, and right--. As long as left <middle and right> middle
            // we have to swap them, that is, to throw small elements to the left, and large ones to the right
            while (s_arr[left] < middle)
                left++;
            while (s_arr[right] > middle)
                right--;
            if (left <= right)
            {
                // as soon as the elements meet, we divide into 2 parts and do the same
                int tmp = s_arr[left];
                s_arr[left] = s_arr[right];
                s_arr[right] = tmp;
                left++;
                right--;
            }
        } while (left <= right); // have we reached the end?
        // recursion starts
        qs(s_arr, first, right);
        qs(s_arr, left, last);
    }
}
  • Вопрос задан
  • 76 просмотров
Пригласить эксперта
Ответы на вопрос 1
NIKITF
@NIKITF
Knows Russian language
Здравствуйте.

Надеюсь это должно натолкнуть Вас на решение задачи:

#include<iostream>
#include<fstream>
#include<string>
#include<vector>
using namespace std;
int convertion(string& s)
{
	if (s.size() > 8) // проверка на восьмибитность(?)
	{
		cerr << "invalid representation";
		exit(-1);
	}
	int out{ 0 }; const int coefficient = 48; 
	for (size_t r = 0; r < s.size(); r++)
	{
		out += ((s[r]-coefficient) * pow(2, s.size()-1 - r));
	}
	return out;
}
int main()
{
	ifstream Q("Digits.txt");
	string temporary;   // буферная строка
	vector<int> array; // массив
	while (Q >> temporary) // считывание из файла
	{
		array.push_back(convertion(temporary)); // помещение в массив чисел с проверкой
	}
	// вывод массива
	for (const auto& v : array)
	{
		cout<< v<<endl;
	}
	Q.close();
	int max1 = INT16_MIN, max2 = INT16_MIN, min1 = INT16_MAX, min2 = INT16_MAX;
	// поиск первых минимума и максимума
	for (const auto& v : array)
	{
		if (v > max1)
		{
			max1 = v;
		}
		else if (v < min1)
		{
			min1 = v;
		}
	}
	// поиск вторых минимума и максимума
	for (const auto& v : array)
	{
		if (v > max2&&v!=max1)
		{
			max2 = v;
		}
		else if (v < min2&&v!=min1)
		{
			min2 = v;
		}
	}
	// вывод чисел:
	cout<<"\n\nMAX:\n" << max1 << endl
		<< max2 << endl
		<<"\n\nMIN:\n" << min1 << endl
		<< min2 << endl;
	return 0;
}
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы