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

R语言else语句中paste0未打印消息问题排查

问题描述

我输入非1、2、3、4的整数时,代码进入了else语句,但没有打印出paste0生成的提示文本,也没报错,请问问题出在哪里?

原代码如下:

escolha <- as.integer(readline(prompt="Enter your choice: "))

if(escolha == 1){
  print("Cool you choose addition!")
} else if (escolha == 2) {
  print("Cool, you choose subtraction!")
} else if (escolha == 3) {
  print("Cool, you choose multiplication!")
} else if (escolha == 4){
  print("Cool, you choose division!")
} else{
  paste0("It's not possible to use ", escolha," as input.")
  escolha<- as.integer(readline(prompt="Choose a valid number (1 a 4): "))
}

num1 <- as.double(readline(prompt="What is the first number? "))

num2 <- as.double(readline(prompt="What is the second number? "))

resultado <- switch (escolha, (num1+num2), (num1-num2), (num1*num2), (num1/num2))

cat("The result is: ", resultado)
问题原因
  1. paste0生成的文本未输出:你仅调用paste0生成了字符串,但没有用print()或cat()将其输出到控制台,所以这段文本只会存在于内存中,不会显示给用户。
  2. 输入校验逻辑有漏洞:当前else语句只处理一次重新输入,若用户再次输入无效数字,代码会直接跳过提示环节,进入后续的数字输入步骤,无法确保输入有效性。
修复后的代码
# 循环校验输入,直到用户输入有效数字
repeat {
  escolha <- as.integer(readline(prompt="Enter your choice: "))
  
  if(escolha == 1){
    print("Cool you choose addition!")
    break
  } else if (escolha == 2) {
    print("Cool, you choose subtraction!")
    break
  } else if (escolha == 3) {
    print("Cool, you choose multiplication!")
    break
  } else if (escolha == 4){
    print("Cool, you choose division!")
    break
  } else{
    # 用cat输出提示文本,换行符\n让提示更清晰
    cat(paste0("It's not possible to use ", escolha," as input.\n"))
  }
}

num1 <- as.double(readline(prompt="What is the first number? "))
num2 <- as.double(readline(prompt="What is the second number? "))

resultado <- switch (escolha, (num1+num2), (num1-num2), (num1*num2), (num1/num2))

cat("The result is: ", resultado)
关键修复点
  • 给paste0的结果添加cat()(或print()),确保提示文本能显示在控制台。
  • 用repeat循环包裹输入校验逻辑,强制用户必须输入1-4的有效数字才会进入后续步骤,彻底避免无效输入直接跳过的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 18:33:36