-
Notifications
You must be signed in to change notification settings - Fork 0
/
hmw_4_2.cpp
129 lines (97 loc) · 2.27 KB
/
hmw_4_2.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
/*
Homework 4_2
Arian Owji
604649619
*/
#include <iostream>
#include <string>
using namespace std;
struct calc_bin_data {
string x1;
string x2;
char op;
};
calc_bin_data calc_parsing(const string& s) {
calc_bin_data a;
unsigned first = s.find("<");
unsigned last = s.find(">");
a.x1 = s.substr(first + 1, last - 1);
string s2 = s.substr(last - first + 1);
a.x2 = s2.substr(first + 2);
a.x2.erase(a.x2.end());
a.op = s2[0];
return a;
}
int convert_binary_to_decimal(const string& s) {
bool negative = 0;
if (s[0] == '-') {
bool negative = 1;
}
long binary_to_convert = stoi(s);
if (negative) {
binary_to_convert *= -1;
}
int decimal_number = 0;
int i = 0;
int remainder;
while (binary_to_convert != 0) {
remainder = binary_to_convert % 10;
binary_to_convert /= 10;
decimal_number += remainder * pow(2, i);
++i;
}
if (negative) {
decimal_number *= -1;
}
std::cout << decimal_number;
return decimal_number;
}
string convert_decimal_to_binary(int n) {
string s;
while (n != 0) {
s = (n % 2 == 0 ? "0" : "1") + s;
n /= 2;
}
return s;
}
int main()
{
char response = 'y';
while (response == 'y') {
calc_bin_data a;
string input;
std::cout << "Enter an expression <in binary format>: ";
std::cin >> input;
a = calc_parsing(input);
int first_number = convert_binary_to_decimal(a.x1);
int second_number = convert_binary_to_decimal(a.x2);
int result_number;
if (a.op == '+') {
result_number = first_number + second_number;
}
else if (a.op == '-') {
result_number = first_number - second_number;
}
else if (a.op == '*') {
result_number = first_number * second_number;
}
else if (a.op == '/') {
result_number = first_number / second_number;
}
else {
result_number = first_number % second_number;
}
string binary_result = convert_decimal_to_binary(result_number);
string result_sign = "";
if (result_number < 0) {
result_sign = "-";
}
std::cout << "--> in binary representation: " << input << "=" << result_sign << binary_result << endl;
std::cout << "--> in decimal representation: <" << first_number << ">" << a.op << "<"
<< second_number << ">=" << result_number << endl << endl;
std::cout << "Continue? <y/n> ";
std::cin >> response;
std::cout << endl;
}
return 0;
}