-2

Please help the green beginner beginner. I am programming a home calculator in js (so I'm not afraid of the terrible eval()) I fixed all (I hope so) errors, but unfortunately there is one that is difficult to fix (if at all possible), in general the eval() method in js and python thinks that: -1 ^ 0.5 = -1 (second way square root) how to fix this ??

found what the main problems were:

1st - it was impossible to write -1 ^ 0.5 (the (^) sign is not supported, only the (**) sign) - you need to indicate this in the instructions

2nd - it was impossible to write -1 ^ 0.5 ("-1" cannot be written, negative numbers must be enclosed in brackets (-1))

3rd - there was an error in this line of code: result = Math.round ((result + Number.EPSILON) * 100) / 100; it should be like this: result = Math.round (result * 100) / 100; (some way of rounding to two decimal places)

I need to do the following:

• you need to complete the error message (alert - "You entered -1 instead of (-1)"

• indicate in the instructions that you cannot enter alphabetic and special characters

• sign (^) - not supported, only sign (**) - to raise a number to a power

• "-1" cannot be written, negative numbers must be enclosed in parentheses (-1)

I am explaining because it will be useful to someone too.

So with eval () everything works as it should, thanks to @GenericUser he directed me in the right direction to find the error, where I started digging after.

here is the code:

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
// Calculating a mathematical expression

    // Input mathematical expression (logic for text-box)
    function mathematical_expression() {   
    $(document).ready(function() {
    $('#secret_box').dialog({
        modal: true,
        autoOpen: true,
        buttons: {
            'Cancel': function() {
                    $(this).dialog('close'); },
            'Accept': function() {
                    $('#mainForm input#target').val($(this).find('#secret_widget').val());
                    console.log('The «Accept» is pressed!-[1.14]'); 
                    $(this).dialog('close'); } } });
                    
    $('#button14').click(function() {
    $('#mainForm input#target').val($(this).find('#secret_widget').val());
    console.log("math expression = " + math_expression1);
    console.log("math expression = " + typeof(math_expression1));
    console.log('The «Accept» is pressed!-[2.14]');
    // $('#secret_box').dialog('close'); 
    }); }); }; 

    // Binding the «Accept» button to the «Enter» key (14)
    function clickPress14(event) {
    if (event.keyCode == 13 && math_expression1 == $('#secret_widget').val()) {
    $('#mainForm input#target').val($(this).find('#secret_widget').val());
    console.log("math expression = " + math_expression1);
    console.log("math expression = " + typeof(math_expression1));
    console.log("The button «Enter» is pressed!-[3.14]");
    $('#secret_box').dialog('close'); 

    try {
    result = eval(math_expression1); 
    result = Math.round((result + Number.EPSILON) * 100) / 100; } // more correct rounding to two decimal places
    catch (SyntaxError) {
    Syntax_Error(); 
    console.log('Catch Error!'); }

    console.log("result = " + result);
    console.log("result = " + typeof(result));
    super_dialog(); }; 

    if (event.keyCode == 13 && math_expression1 != $('#secret_widget').val()) {
    console.log("math expression = " + math_expression1);
    console.log("math expression = " + typeof(math_expression1));
    console.log("The button «Enter» is pressed!-[3.14]"); }; }

    // value_immediately14
    function value_immediately14() {
    $(document).ready(function() {
    math_expression1 = $('#secret_widget').val();
    console.log("math expression = " + math_expression1);
    console.log("math expression = " + typeof(math_expression1));
    $('#button14').click(function() {
    $('#mainForm input#target').val($(this).find('#secret_widget').val());
    $('#secret_box').dialog('close'); 

    try {
    result = eval(math_expression1); 
    result = Math.round((result + Number.EPSILON) * 100) / 100; } // more correct rounding to two decimal places
    catch (SyntaxError) {
    Syntax_Error(); 
    console.log('Catch Error!'); }
    
    console.log("result = " + result);
    console.log("result = " + typeof(result));
    super_dialog(); }); }); } 

// Secret result 
function super_dialog() {
$(document).ready(function() {
alert("The result of your math expression: " + math_expression1 + " will be is - " + result);

function alert(alert_text) {
$("#super_dialog").show();
$("#secret_text").text(alert_text); }

$("#secret_close").click(function() {
$("#super_dialog").hide(); 
window.location.reload(); }); }); }

// Syntax_Error Alert! 
function Syntax_Error() {
$(document).ready(function() {
alert("The characters you entered are completely"
+ "\ndifferent from the mathematical expression."
+ "\nSo come on already bro... Adios mi amigo!!!");

function alert(alert_text) {
$("#alert_dialog10").show();
$("#alert_text10").text(alert_text); }

$("#alert_close10").click(function() {
$("#alert_dialog10").hide(); 
window.location.reload(); }); }); }

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
// Warning! Incorrect input!

//Warning! Incorrect input!
function warning() {
if (sum == 0 || period == 0 || percent == 0) {
alert_result8(); }
else if (sum == 0 && period == 0 && percent == 0) {
alert_result8(); }
else if (X == 0 || Y == 0 || P == 0) {
alert_result8(); }
else if (X == 0 && Y == 0 && P == 0) {
alert_result8(); }
else if (Z == 0 && N == 0) {
alert_result8(); } }

// Warning! Incorrect input! (alert-box)
function alert_result8() {
$(document).ready(function() {
alert("You entered either the first or the second number incorrectly," 
+ "\nor you entered both numbers incorrectly at once! You may" 
+ "\nalso have entered zero or both numbers as zeros!");

function alert(alert_text) {
$("#alert_dialog8").show();
$("#alert_text8").text(alert_text); }

$("#alert_close8").click(function() {
$("#alert_dialog8").hide(); }); }); }
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
  • 3
    `^` is not "square root". It's a bitwise XOR. [What does the ^ (caret) symbol do in JavaScript?](https://stackoverflow.com/q/3618340) – VLAZ Dec 17 '21 at 14:41
  • Welcome to [so]. Please take a [tour] of the site, read [ask] a good question and how to create a [mcve]. Then come back to your question and reformulate it (preferably with code samples, the provided input and the expected output) in order to get a (useful) answer. Before posting a question, [search](/search) the site and make sure a similar question wasn't already answered. **Please also note that [so] is not a coding service where you can throw your homework and wait for others to do it for you**. Show what you have tried and where you got stuck to maximize the chances to get help. – axiac Dec 17 '21 at 14:46
  • 1
    You say _"I am programming a home calculator in js (so I'm not afraid of the terrible eval())"_ -- it seems that you do not understand why `eval()` should be a avoided. Your code is the perfect example when `eval()` must not be used. You pass to `eval()` a string received from outside the code, a string that can contain any JavaScript code. Code that runs with the same permissions as your code. Code that does whatever its author wants to do, but in your name. – axiac Dec 17 '21 at 14:50
  • 1
    @axiac another reason why it should be avoided is also present in this question. If you assume that JS code should work as a mathematical evaluator, you'd be in for a surprise for calculating powers with a `^`. Even outside of that there are many traps and gotchas that mean that JS code is not the same as a mathematical expression. Just transforming `-1 ^ 0.5` to `-1 ** 0.5` reveals another pitfall - you cannot use a unary minus with the power of operator. Because at the language level, it's not easy to distinguish whether you want `(-1)**0.5` or `-(1**0.5)` so it's just an error. – VLAZ Dec 17 '21 at 14:55
  • @meagar [I'm not lying](https://i.imgur.com/JgNmPWV.png) - [Why is -1**2 a syntax error in JavaScript?](https://stackoverflow.com/q/43556752) – VLAZ Dec 17 '21 at 14:59
  • @axiac The problem with eval, is not going against what the author wants, it's going against what the user wants. I can press Ctrl + Shift + I, and make a website do what the heck I like. Eval is dangerous if it executes code from another domain, that you have no control off. eg, You should never say `eval` code that you acquired from say an external `fetch` request. So, in my opinion using `eval` for a calculator that get's it inputs from the user is not a security concern, even if said app was run live on the web. Of course things change again, if eval was run in say `node.js`... – Keith Dec 17 '21 at 15:02
  • @VLAZ Apologies, I had no idea JavaScript had such an operator, or that it considered unary minus ambiguous. `-4 ** 5` presents no more problem in Ruby/Python than `-4 * 5`. – user229044 Dec 17 '21 at 15:02
  • @Keith And your last sentence is why `eval` *is* dangerous in this case, and should be avoided in virtually all cases. You should be free to move your math expression evaluator from the front-end to the back-end without introducing a severe RCE vulnerability. Placing `eval` into your codebase where it's "safe" is almost always a vulnerability waiting to happen. – user229044 Dec 17 '21 at 15:05
  • @meagar Portability is a good reason, yes. But I certainly wouldn't say -> `Your code is the perfect example`, when if fact it's a really bad example of why it's bad. :) – Keith Dec 17 '21 at 15:14
  • @axiac, Unfortunately my problem is a rather non-trivial problem, of course I was looking, this is the first question I asked on stackoverflow, before that I had been finding all my questions for a year and a half myself and correcting all my mistakes myself. – Dimetriy1_2_1_2 Dec 17 '21 at 15:23
  • By the way, this proleb does not only apply to eval (), for example, python itself also calculated the answer in a complex notation to -1 ** 0.5 (I prohibited this with conditions), but in this construction I have only one essentially variable and the conditions will not help me. I also know that there are new mathematical developments in the field of calculating the square root of negative numbers. – Dimetriy1_2_1_2 Dec 17 '21 at 15:23
  • If you want to be able to handle complex numbers, you might find this handy -> https://www.npmjs.com/package/complex.js eg. sqrt of -1, will give you 0 with imaginary 1.. which is `i` so looks good.. :) – Keith Dec 17 '21 at 15:45
  • `-1 ** 0.5` is `sqrt(-1)` i.e. the [imaginary unit, also known as `i`](https://en.wikipedia.org/wiki/Imaginary_unit) and there is nothing new about it. The theory of complex number has been developed [almost 500 years ago](https://en.wikipedia.org/wiki/Complex_number#History). – axiac Dec 17 '21 at 16:30

1 Answers1

2

In JavaScript, ^ is the Bitwise XOR operator. If you want to do exponentiation, you can use either Math.pow or ** operator.

console.log(2 ** 2);
console.log(Math.pow(3, 2));
GenericUser
  • 3,003
  • 1
  • 11
  • 17
  • Thank you for your answer, but unfortunately it is in this code that you cannot do this, my input goes directly to eval() (and there is a ban on entering other characters). The method you suggested is used in another mode of my calculator (through three variables), but it was interesting to work with eval(). Bitwise XOR (^) didn't know, thanks! – Dimetriy1_2_1_2 Dec 17 '21 at 14:57