CS50马里奥台阶代码报错求助:data argument等格式与语法错误
Fixing Your CS50 Mario Staircase Code Issues
Let's break down each error in your code and fix them step by step:
1. Format String Mismatches in printf
The first two errors happen because you're passing extra arguments to printf that the format string doesn't use:
- For
printf(" ", n - 1 - i);: You’re trying to printn-1-ispaces, but the format string" "has no placeholder for the integer argument. A clean way to print a specific number of spaces is using%*s— this tellsprintfto use the integer as the width of an empty string, which fills with spaces:printf("%*s", n - 1 - i, ""); - For
printf("#", i + 1);: You want to printi+1hash symbols, but the format string"#"doesn’t need thei+1argument. You can either use a loop to print each#, or use a formatted print with a long string of hashes:
Theprintf("%.*s", i + 1, "########################");%.*suses the integer as the length of the hash string to print (the long hash string covers all possible heights up to 8).
2. Mismatched Curly Braces
The third error is a missing closing } for your main function. Your outer for loop closes with a }, but you need one more to wrap up the entire main block.
Corrected Full Code
Here are two working versions of your code:
Version 1: Using Formatted printf Calls
#include <stdio.h> #include <cs50.h> int main(void) { int n; do { n = get_int("Height: "); // height determines how many steps are to be made } while (n < 1 || n > 8); for (int i = 0; i < n; i++) { // Print leading spaces printf("%*s", n - 1 - i, ""); // Print hashes printf("%.*s", i + 1, "########################"); // New line after each step row printf("\n"); } }
Version 2: Using Explicit Nested Loops (Great for Learning)
If you prefer clearer, step-by-step loops (which is totally appropriate for CS50):
#include <stdio.h> #include <cs50.h> int main(void) { int n; do { n = get_int("Height: "); } while (n < 1 || n > 8); for (int i = 0; i < n; i++) { // Print leading spaces for (int j = 0; j < n - 1 - i; j++) { printf(" "); } // Print step hashes for (int k = 0; k < i + 1; k++) { printf("#"); } printf("\n"); } }
内容的提问来源于stack exchange,提问作者unijee
相关产品推荐
相关产品推荐

