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:
Valid positive input:
convierte(100)Output:
Kens Shakus 3.322259 0.55Negative input (error case):
convierte(-5)Output:
Error in convierte(-5) : Error: Input must be a positive number!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
相关产品推荐
相关产品推荐

