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

R语言实现厘米转Kens/Shakus:输出优化与异常处理需求

Modified R Function for cm to Kens/Shakus Conversion

Let's tweak your function to hit all your requirements perfectly. Here's the adjusted version with explanations for each change:

Key Improvements:

  • Added input validation to catch non-positive values and throw a clear error
  • Fixed the conversion coefficients to match your specified values (1 ken = 30.1 cm, 1 shaku = 181.1 cm)
  • Formatted the Shakus result to 2 decimal places as requested
  • Returned a named vector so the output is easy to interpret

Final Working Code:

convierte <- function(cc) {
  # Validate input: must be a positive numeric value
  if (!is.numeric(cc) || cc <= 0) {
    stop("Error: Input must be a positive number!")
  }
  
  # Calculate conversions using correct rates
  kens <- cc / 30.1
  shakus <- round(cc / 181.1, 2)  # Round Shakus to 2 decimal places
  
  # Return a named vector for clarity
  return(c(Kens = kens, Shakus = shakus))
}

Test Cases to Verify:

  1. Valid positive input:

    convierte(100)
    

    Output:

    Kens     Shakus 
    3.322259   0.55 
    
  2. Negative input (error case):

    convierte(-5)
    

    Output:

    Error in convierte(-5) : Error: Input must be a positive number!
    
  3. Zero input (error case):

    convierte(0)
    

    Output:

    Error in convierte(0) : Error: Input must be a positive number!
    

This function now handles edge cases correctly, uses the right conversion factors, and returns a clean, labeled result as you needed.

内容的提问来源于stack exchange,提问作者Adrián

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 09:04:01