+ 1

Is it possible to convert "char" variables to operators?

Let's say I need to run a completely variable expression. Is there any way to do it more or less as follows, where 'a' and 'b' are numbers and 'operator' can be '+', '-', '/', '*' or '%'? int result = a operator b; It's a pretty silly question, I know, but I have not found a solution yet. The only way I got it was by checking which character the 'operator' variable holds and doing a series of calculations using a 'switch' structure for each one.

12th Apr 2018, 11:33 AM
rfPeixoto
rfPeixoto - avatar
4 Antworten
+ 6
Since you included Ruby in the tags I decided to make a small example with three cases. Note that this makes use of several Ruby features that may not be present in other languages, and that even the first solution that is raised within the code is not recommended in almost any language. https://code.sololearn.com/cn5xE990Immi/?ref=app
12th Apr 2018, 1:21 PM
Mickel
Mickel - avatar
+ 1
Chars is represented by ASCII numbers. Then yes.
12th Apr 2018, 11:42 AM
Bartosz Pieszko
Bartosz Pieszko - avatar
+ 1
yes, you might need to convert them to their ascii code first depending on language and then convert them back into characters, but it is doable
12th Apr 2018, 12:37 PM
hinanawi
hinanawi - avatar
+ 1
Thank you very much, people. o/
12th Apr 2018, 1:36 PM
rfPeixoto
rfPeixoto - avatar