Guy
Guy

Reputation: 6522

Dividing integer to get all of it's numbers and sum them

I'm trying to code a script that will take an integer that a user enters and then sum all of it's numbers. The integer must be between 1-99

Example:

If a user enters 27

Output: 9

Here's the code:

@ECHO OFF
SET /p number="Enter a number: "
SET sum=0

IF %number% GTR 9 (
SET /a temp=%number% %% 10
SET /a sum+=%temp%
SET /a number/=10
SET /a sum+=%number%
) ELSE (
SET /a sum+=%number%
)

echo %sum%

So let's say for example the number entered is 19, it should first do 19 % 10 to get the "9" and then 19 / 10 to get the 1, summing them both and getting 10. But when I actually run this code it returns 19 (in case I enter 19)

Upvotes: 0

Views: 54

Answers (3)

Endoro
Endoro

Reputation: 37589

@echo off &setlocal disableDelayedExpansion
SET /p "var=Enter var (1-99) "
set /a var=%var:~0,1%+%var:~1,1% 2>nul
echo %var%

Upvotes: 0

MC ND
MC ND

Reputation: 70943

If the numbers are limited to the range 1-99, the calc is direct

set /a "sum=%number% / 10 + %number% %% 10"

%number% / 10 will return the left digit if any, 0 if %number% is less than 10

%number% %% 10 will return the right digit

Just sum them

Upvotes: 1

Magoo
Magoo

Reputation: 80113

Within a block statement (a parenthesised series of statements), the entire block is parsed and then executed. Any %var% within the block will be replaced by that variable's value at the time the block is parsed - before the block is executed.

Hence, the value assigned to temp is not evaluated as you expect.

You should look for the many SO articles about delayed expansion and find out about batch substrings. This will make your task easier.

And don't use temp as a user-variable, however logical it may seem. temp is a directory pointer which tells the system where to store temporary files. Not a good idea to change it.

Upvotes: 0

Related Questions