在R语言中编写无参数函数:获取用户输入整数并打印1-10乘法表
R Function to Generate a Multiplication Table for a User-Input Integer
Got it, let's put together that R function you need! Here's a straightforward, user-friendly implementation that prompts for an integer, validates the input, and prints a clean multiplication table from 1 to 10:
multiplication_table <- function() { # Ask user for input and convert to integer user_input <- readline(prompt = "Please enter an integer: ") num <- as.integer(user_input) # Quick check to make sure input is a valid integer if (is.na(num)) { cat("Whoops, that doesn't look like an integer. Give it another go!\n") return(invisible(NULL)) } # Print the table header and rows cat(paste("Multiplication table for", num, "\n")) cat("---------------------------\n") for (i in 1:10) { product <- num * i cat(paste(num, "x", i, "=", product, "\n")) } }
Breakdown of how it works:
- The function uses
readline()to get input directly from the console, then converts it to an integer withas.integer(). - It includes a simple validation step: if the input can't be turned into an integer (like if someone enters a word or decimal), it shows a friendly error message and stops.
- A
forloop runs from 1 to 10, calculates the product each time, and usescat()to print neatly formatted lines for the table.
Example run:
Call the function, then enter an integer when prompted:
multiplication_table()
Sample output when you type 6:
Please enter an integer: 6 Multiplication table for 6 --------------------------- 6 x 1 = 6 6 x 2 = 12 6 x 3 = 18 6 x 4 = 24 6 x 5 = 30 6 x 6 = 36 6 x 7 = 42 6 x 8 = 48 6 x 9 = 54 6 x 10 = 60
内容的提问来源于stack exchange,提问作者Sloshie
相关产品推荐
相关产品推荐

