+ 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.
4 Answers
+ 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
+ 1
Chars is represented by ASCII numbers. Then yes.
+ 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
+ 1
Thank you very much, people. o/