Johnny Mayhew
Johnny Mayhew

Reputation: 91

ECHO Command with variable

I'm new to batch and I'm trying to make a speed/distance/time calculator. The code works fine until I try to echo the total. Here's my code:

@ECHO off
COLOR 0f
TITLE Speed Distance Time Calculator

:BEGIN
SET /P type="Calculate speed/distance/time? (S/D/T): "
CLS

IF /I "%type%"=="s" (
    SET /P distance="Distance: "
    CLS
    SET /P dUnits="Distance units (mile/m/km):"
    CLS
    SET /P time="Time: "
    CLS
    SET /P tUnits="Time units (h/s):"
    CLS
    SET total=%distance%/%time%
    ECHO %total%
)

It outputs:

ECHO is off

I've looked around for answers and have tried "enabledelayedexpansion" but it did not work.

Upvotes: 1

Views: 264

Answers (1)

Sam
Sam

Reputation: 3480

To do division (or any arithmetic operation) in a batch file using the SET command, you have to specify the /A switch. Additionally, you'll need to turn on delayed variable expansion, since you will be dynamically changing variables in the batch file, and then using them.

When using delayed expansion variables you must reference them with ! instead of %. The exclamation marks tell the command processor that you want that particular variable's expansion to be delayed. Any variables that use percentage signs will be expanded at initial parse time.

So at the top of your batch file, under the @ECHO off, turn on delayed expansion:

SETLOCAL EnableDelayedExpansion

Then perform the calculation like so:

SET /A total=!distance!/!time!
ECHO !total!

Upvotes: 1

Related Questions