/*===================================================== * Перевод двоичного кода в десятичный методом сложения * Создал: xXDima212DimaXx * * Лицензия: Свободный доступ и модификация * * Как это работает? * * Создается массив данных (пользовательские данные), * в который пользователь заносит двоичное значение. * Затем создается переменная кратная 2 (ее значение * зависит от длины введенных данных. Например для * 1 байта это 128). Затем если первая цифра данных * равна 1, к конечному значению прибавляется * значение этой переменноя, и наоборот если первая * цифра равна 0, то прибавления не происходит. * Затем та переменная (кратная 2) делится на 2 и * действие повторяется, только уже проверяется вторая * цифра в двоичном значении. Цикл выполняется пока * переменная, которая кратна 2 не достигает значения 1 * и пока в двоичных данных не закончились цыфры для * проверки (их количество равно размеру массива с * пользовательскими данными). После этого полученное * значение выводиться на экран. *===================================================*/
#include<iostream>
#include<cstdlib>
#include<limits>
#include<cstring>intconvert(char val[]);
intmain (void) {
// Значение, которое вводит пользователь (1 байт)char value[8] = {};
// Для проверки длины (Debug)// char vb[] = "";// Запрос пользовательского ввода
std::cout << "Enter 1 byte: ";
std::cin >> value;
// Debug// if (vb.length() == 8) {// value = vb;// } else {// std::cout << "Incorect length of data. You can use only 8 digits!" << std::endl;// return 1;// }// Исправление бага при вводе неверного типа данныхif ((std::cin.fail() == 0)) {
// Если пользователь ввел правильный тип данных, продолжаем выполнение
} else {
// Если тип данных некорректный, то завершаем программу, выдав ошибку
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Incorect type of data. Value \"" << value << "\" not allowed. You can use only 0 or 1!" << std::endl;
return1;
}
for (int g = 0; g < sizeof(value); g++) {
if ((value[g] == '0') || (value[g] == '1')) {
} else {
std::cout << "Incorect type of data. Value \"" << value << "\" not allowed. You can use only 0 or 1!" << std::endl;
return1;
}
}
// Debug// std::cout << value << std::endl;// Вызов условной функции, которая проверяет значение введенные данные и выводит результат на экран
std::cout << "Decoded value: " << convert(value) << std::endl;
return0;
}
// Условная функция, которая проверяет значение переменной valintconvert(char val[]) {
// Debug// std::cout << val << std::endl;// R - конечное значение, которое выведет программаint r = 0;
// J для откладки. По желанию можно удалить и использовать val[int] в проверочном условииint j = 0;
// plus - переменная, помогающая вычислить значение r (см. код ниже)int plus = 256;
// Цикл проверки. Выполняется n-ое кол-во раз, где n - число Бит (1 Байт = 8 Бит)for (int i = 0; i < sizeof(val); i++) {
/*===================================================== * Раскоментировать если программа работает неправильно * (Режим откладки) * std::cout << "[" << i << "]" << "\t"; * std::cout << val[i] << "\t"; *===================================================*/// J для откладки. По желанию можно заменить на val[int] в проверочном условии
j = val[i];
/*===================================================== * Раскоментировать если программа работает неправильно * (Режим откладки) * std::cout << "Debug j: " << j << "\t"; * std::cout << "Debug j - 48: " << (j - 48) << "\t"; *===================================================*/// Необходимо для расшифровки двоичного кода методом сложения
plus = plus/2;
// Проверкаif ((j - 48) == 1) {
r = r + plus;
// Debug// std::cout << "\t 1\t" << r << " Debug plus: " << plus << std::endl;
} else {
// Debug// std::cout << "\t 0\t" << r << " Debug plus: " << plus << std::endl;
}
}
// Возврат результата выполнения программыreturn r;
}
Example: Celsius to Fahrenheit (Exam task)
Path: cpp/lesson15/cf.cpp
#include<iostream>
#include<cstdlib>
#include<limits>usingnamespacestd;intmain (void)
{
cout << "Celsius to Fahrenheit" << endl;
int N = 0;
int M = 0;
cout << "From: ";
cin >> N;
cout << "To: ";
cin >> M;
for (;N < M; N++) {
cout << N << "°C\t" << (N*1.8)+32 << "°F" << endl;
}
return0;
}
// Base i/o library
#include<iostream>// Other useful libraries
#include<cstdlib>// C Standard General Utilities Library
#include<limits>// Numeric limits
#include<cmath>// Math library
#include<cstring>// String type library
#include<ctime>// C++ time library
#include<fstream>// Filesystem library//Connect your libraries and .h, .hpp files
#include 'file1.h'
#include 'file2.hpp'
// Execute this code once (e.g if you connect files, which contain same functions)
#pragma once
// You can implement cinst hereconstint INTVALUE = 4545;
// Namespace STDusingnamespacestd;// Function prototypesvoidmyFunc1 ();
intmyFunc2 (int input_value);
charmyFunc3 ();
// Main functionintmain () {
// Variablesint a = 0; // Integerfloat b = 0.25; // Float
string c = "Hello, world!"; // String (require cstring library)char d = 'a'; // Charint arr[5] = {1, 2, 3, 4, 5}; // Integer array with 5 elementschar e = "Hello, world!"; // Char arrayconstint AGE = 18; // You can not modify this integer, because it is constshortint f = 136732; //Integer without decimallongint g = 13287387278; // Long integerunsigned h = 4294967295; // This integer always more than 0bool j = true; // Boolean/******************************************************* * Base operators and output: * * * Base operators: * +, -, *, /, % * * * i++ ............. i + 1 * i-- ............. i - 1 * i += 2 ...... i = i + 2 * i -= 5 ...... i = i - 5 * * Conditionals operators: * >, <, >=, <=, ||, && * * * Cmath operators * pow(number, power); * mod(number); * cos(number); * sin(number); * tg(number); * ctg(number); * etc... * * \n = endl; = new linw * \t = tab * * * Boolalpha and noboolalpha * bool val = true; * cout << boolalpha << val << endl; // Output true instead 1 * cout << noboolalpha << val << endl; // Output 1 instead true * * STD:: * If you don't implement 'using namespace std', you must add std:: before std commands, * because you can use other namespaces (e,g std::cout << "Hello!" << std::endl;) * ******************************************************/// Random (Require <ctime> library)srand(time(NULL));
rand() % 8 + 7; // Rand from 7 to 15// Inputint x = 0;
cin >> x;
// Fix linux bug with incorrect input (Require <limits> library)if ((cin.fail() == 0)) {
// Correct data type
} else {
// Incorrect data type
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
// Show error
cout << "Incorect type of data. Value \"" << value << "\" not allowed. You can use only 0 or 1!" << endl;
return1; // Finish program with error
}
// Output
cout << "X = " << x << endl;
// *VARIABLE - show address in RAM (link)
cout << *x << endl;
// &VARIABLE - show normal value (unlink if linked, use with *VARIABLE)
cout << &x << endl;
// Conditionsif (a == 1) {
// True
} elseif (a == 2) {
// First condition false, but second true
} else {
// False
}
// Loop forfor (int i = 0; i < 10; i++) {
// Repeat for 10 times
}
// Loop whilewhile (/* Condition */) {
// Repeats only if condition in the while () = true
}
// Loop do whiledo {
// Repeats only if condition in the while () = true
} while (/* Condition */);
// Catch errorstry {
// Code, which may contain errors
} catch (e) {
// Alternative code here (e.g show error message)
}
// Write to file (Require <fstream> library)
ofstream file;
file.open("file");
if (file.is_open())
{
file << "Some text here..." << endl;
file.close();
} else cout << "unable to open file";
// Read file (Require <fstream> library)
string data;
ifstream file;
file.open("file");
if (file.is_open())
{
file >> data;
cout << data << endl;
file.close();
} else cout << "unable to open file";
// Execute system commandsystem("command");
// Clear terminal Linuxsystem("clear");
// Clear terminal Windowssystem("CLS");
// Returnreturn0;
/* * return 1; - Program finished with error or force closed * return 0; - Program finished successfully * return -1; - Program finished with unknown error * return 2; - Program finished and needs restart * * You can override or add your own finish codes*/
cout << "Hello" << endl; // This string will be ignored because program finish after return
}
// Void functionvoidmyFunc1 () {
// Your code here// Void function don't requirs return
}
// Int functionintmyFunc2 (int input_value) {
// Your code herereturnint;
}
// Char functioncharmyFunc3 () {
// Your code herereturnchar;
}
Other useful codes:
Bubble sort:
#include<iostream>usingnamespacestd;constint SIZE = 20;
voidbuble(int mas[], int SIZE);
intmain()
{
int mas[] = {5, 4, 3, 2, 1, 6, 3, 9, 10, 22, 55, 64, 17, 26, 81, 678, 73, 97, 110, 22};
for(int i = 0; i < SIZE; i++)
{
cout << mas[i] << "";
}
cout << endl;
buble(mas, SIZE);
for(int i = 0; i < SIZE; i++)
{
cout << mas[i] << "";
}
cout << endl;
}
voidbuble(int mas[], int SIZE)
{
for(int i = 0; i < SIZE; i++)
{
for(int a = i+1; a < SIZE; a++)
{
if(mas[i] > mas[a])
{
int x = mas[i];
mas[i] = mas[a];
mas[a] = x;
}
}
}
}
Select sort:
#include<iostream>usingnamespacestd;voidswap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
voidselectionSort (int arr[], int n)
{
int min;
for (int k = 0; k < n-1; k++)
{
min = k;
for (int j = k + 1; j < n; j++)
{
if (arr[j] < arr[min]) min = j;
}
swap(&arr[min], &arr[k]);
}
}
voidprintArray(int arr[], int size) {
for (int i = 0; i < size; i++)
{
cout << arr[i] << "";
}
cout << endl;
}
intmain() {
int arr[] = {5, 2, 42, 6, 1, 3, 2};
int n = sizeof(arr)/sizeof(arr[0]);
selectionSort(arr, n);
printArray(arr, n);
return0;
}