创建一个随机数并检查它是奇数还是偶数

创建一个随机数并检查它是奇数还是偶数

本文介绍了创建一个随机数并检查它是奇数还是偶数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望创建一个批处理文件,在运行时,创建一个0到100之间的随机整数,然后通过if语句运行它,检查它是奇数还是偶数。
我一直遇到麻烦,所以这就是我目前的情况。

I am looking to create a batch file that, when ran, creates a random integer from 0 to 100 and then runs it through an if statement that checks whether it is odd or even.I've been having some trouble, so here is what I have so far.

@echo off
set /a num=%random% %%100 +1
if ( num % 2 == 0 ) {
     //even
}
else
{
    //odd
}

我得到的错误是 - num此时出乎意料

The error I get is - "num was unexpected at this time"

推荐答案

@ECHO OFF
SETLOCAL
set /a num=%random% %%100 +1
SET /a nummod2=num %% 2
IF %nummod2% == 0 (ECHO %num% is even) ELSE (ECHO %num% is odd)

GOTO :EOF

常规 IF 语法是如果[not] operand1 == operand2 somethingtodo 其中operand1和operand2都是字符串。如果字符串包含分隔符,如 或其他对批处理具有特殊含义的字符,则字符串必须为用引号括起来。

Conventional IF syntax is if [not] operand1==operand2 somethingtodo where operand1 and operand2 are both strings. If the strings contain separators like or other characters that have a special meaning to batch then the string must be "enclosed in quotes".

从根本上说,如果比较字符串。运算符必须是一组固定的运算符之一[== equ neq gtr geq lss leq]因此 cmd 反对 num 预期运营商的位置。

Fundamentally, if compares strings. The operator must be one of a fixed set of operators [== equ neq gtr geq lss leq] hence cmd was objecting to num where it expected an operator.

如果语句的参数,则无法在内执行计算。

A calculation cannot be performed within a if statement's parameters.

%% 是执行 mod 操作所必需的,因为%是一个特殊字符,本身需要通过%进行转义。

%% is required to perform the mod operation, since % is a special character that itself needs to be escaped by a %.

请注意, {和} 是普通字符,对批处理没有特殊意义,必须遵循备注

Note that { and } are ordinary characters with no special meaning to batch and remarks must follow

rem remark string

有一个常用的漏洞利用

::comment

实际上是一个破损的标签,可能会产生无法预料的副作用(比如结束代码块)

actually, a broken label, which can have unforeseen side-effects (like ending a code-block)

这篇关于创建一个随机数并检查它是奇数还是偶数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 16:04