You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Racket赌博模拟中条件语句无法匹配字符串相等性问题

问题原因与解决方法

问题出在类型不匹配:你定义的c是从符号列表'(red black)中选取的符号(symbol),而bet是通过read-line获取的字符串(string)。Racket中,符号'red和字符串"red"是完全不同的类型,equal?不会认为它们相等,所以条件永远不满足,始终输出"L"。

解决方法(两种可选)

方法1:将颜色列表改为字符串类型

直接把颜色列表换成字符串数组,让c和bet保持同类型(都是字符串),这样equal?就能正确匹配:

(define (ro)
  (define bet (string-trim (read-line)))
  (define n (+ (random 36) 1))
  ; 把符号列表改为字符串列表
  (define c (list-ref '("red" "black") (random 2)))
  
  (display (string-append bet " " c " "))
  
  (cond
    [(equal? bet c) (display "W")]
    ; 取消注释后,"1-18"作为字符串直接匹配
    [(equal? bet "1-18") (if (<= n 18) (display "W") (void))]
    [else (display "L")]
  ))

(ro)

方法2:将输入字符串转为符号

把用户输入的bet转换成符号,和c的类型保持一致。注意带特殊字符的输入(比如"1-18")需要用竖线包裹符号:

(define (ro)
  ; 将输入的字符串转为符号
  (define bet (string->symbol (string-trim (read-line))))
  (define n (+ (random 36) 1))
  (define c (list-ref '(red black) (random 2)))
  
  ; 输出时需要把符号转回字符串
  (display (string-append (symbol->string bet) " " (symbol->string c) " "))
  
  (cond
    [(equal? bet c) (display "W")]
    ; 带特殊字符的符号需要用|包裹
    [(equal? bet '|1-18|) (if (<= n 18) (display "W") (void))]
    [else (display "L")]
  ))

(ro)

推荐方案

优先选择方法1,因为用户输入本身是字符串,保持类型一致更直观,也不需要处理特殊符号的转换问题,代码更简洁易维护。

内容的提问来源于stack exchange,提问作者Firstmine

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 02:52:42