0

When i execute my program and put in something like 1280000000*20 it gives me -169803776 when it should be 25600000000, when i then try 25600000000/20 it gives me -1698037766 which is different. This shows there is something wrong with my calculator because the laws of maths say when a*b=c, b/c=a which isnt true in this situation. The calculations are also incorrect.

I've tried putting the same code into python (different language) and it works fine so i think its something to do with batch itself.

echo off
cls

:start
cls
echo Welcome to the calculator
echo.
echo Choose one of the of the following
echo.
echo 1. Multiplication
echo 2. Division
echo.
set /p choose=Choose a number: 

IF %choose%==1 (
   goto multiply
) ELSE IF %choose%==2 (
   goto divide
) ELSE (
    goto error
)

:error
cls
echo THAT ISNT AN OPTION!!
echo.
pause
goto start

:multiply
cls
echo Pick 2 numbers to multiply
echo.
set /p a=Number 1: 
set /p b=Number 2: 
set /a c=%a%*%b%
cls
echo %a% x %b% = %c%
pause
goto start

:divide
cls
echo Pick 2 numbers to divide
echo.
set /p a=Number 1: 
set /p b=Number 2: 
set /a c=%a%/%b%
cls
echo %a% / %b% = %c%
pause
goto start

I expect the output of 1280000000*20=25600000000, but the actual output is -169803776. This number changes every time to a negative for some reason.

jallmen
  • 136
  • 1
  • 7
  • batch/cmd is limited to 32bit accuracy in calculation.. you can use `vbs` to work with larger numbers. – Gerhard Apr 17 '19 at 10:24
  • `Set /A`, as you're using, can only handle 32-bit integers, the range is therefore up to 4,294,967,295 _(2³² − 1)_. – Compo Apr 17 '19 at 10:26
  • I suggest also reading [How to stop Windows command interpreter from quitting batch file execution on an incorrect user input?](https://stackoverflow.com/a/49834019/3074564) explaining very detailed why it is better to use `choice` for a choice menu instead of `set /P`. – Mofi Apr 17 '19 at 10:43
  • 1
    @Compo Do you have a I link showing me code how `set /A` can be used for 32 bit __unsigned__ integer arithmetic without extra code to workaround 32 bit __signed__ integer arithmetic as used by `set`. Even `set /A "Number=1<<31"` results in `Number` having string value `-2147483648` as `0x80000000` is interpreted as minimum negative value. And `set /A "Number=0xFFFFFFFF"` is interpreted as `-1` and not as `4294967295`. – Mofi Apr 17 '19 at 10:51
  • I'm with @Mofi, as negative numbers are stored as [two's complement](https://en.wikipedia.org/wiki/Two%27s_complement) the maximum number is the one with bit 32 not set, see `set /a "0x7FFFFFFF` what returns `2147483647` As for OPs question `set /A` should return an out of bounds error when exceeding the int32 range, but doesn't for compatibility reasons I think. –  Apr 17 '19 at 11:20

0 Answers0