如何在Hackerrank生成R语言输出?FizzBuzz代码报错求助
Hey there! Let's tackle your two HackerRank R questions one by one.
1. How to Create R Output for HackerRank
HackerRank expects your R code to output results directly to standard output (stdout) without extra formatting fluff (like the [1] prefix that print() adds). Here's what you need to know:
- Use
cat()instead ofprint():cat()writes directly to stdout and lets you control formatting exactly. - For multi-line output (like most problems require), use
sep = "\n"to put each result on its own line. - Example: If you need to output numbers 1 to 5, just run
cat(1:5, sep = "\n")—this will print each number on a separate line, which is exactly what HackerRank looks for.
2. Fixing Your FizzBuzz Code for HackerRank
Let's walk through the issues in your code and fix them step by step:
Key Problems in Your Original Code
- Redundant
stdin2initialization: You don't need to predefinestdin2withc(NA, n)—this creates a vector of the wrong length and leads to unnecessary complexity. - Incorrect
write()usage:cat()already outputs directly to stdout, and its return value isNULL. Callingwrite(cat(...), stdout())is trying to writeNULLto stdout, which is why you're getting errors. This line is completely unnecessary. - Formatting issue:
cat(stdin2, "\n")will print all elements in one line followed by a single newline. HackerRank expects each result on its own line, so you needsep = "\n"instead. - Minor logical tweak: In your nested
ifelse, you returni(the loop index) instead ofset[i]—it works here becausesetis 1 to n, but it's better to use the actual number for clarity and robustness.
Corrected Code
fizzBuzz <- function(n) { set <- seq.int(1, n, 1) # Initialize a character vector to store results (consistent type) result <- character(length(set)) for (i in seq_along(set)){ num <- set[i] if (num %% 15 == 0) { result[i] <- "FizzBuzz" } else if (num %% 3 == 0) { result[i] <- "Fizz" } else if (num %% 5 == 0) { result[i] <- "Buzz" } else { # Convert number to character to keep vector type consistent result[i] <- as.character(num) } } # Print each result on a separate line cat(result, sep = "\n") }
What Changed?
- Replaced nested
ifelsewith plainif-elseblocks for better readability. - Used
seq_along(set)instead of1:length(set)—this is safer because it handles empty vectors correctly. - Initialized
resultas a character vector to avoid mixing numeric and character values (which can cause unexpected behavior). - Removed the broken
write()call and usedcat(..., sep = "\n")to output each result on its own line, matching HackerRank's requirements.
内容的提问来源于stack exchange,提问作者eknagi
相关产品推荐
相关产品推荐

