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

在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 with as.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 for loop runs from 1 to 10, calculates the product each time, and uses cat() 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 04:09:22