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

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 print n-1-i spaces, 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 tells printf to 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 print i+1 hash symbols, but the format string "#" doesn’t need the i+1 argument. You can either use a loop to print each #, or use a formatted print with a long string of hashes:
    printf("%.*s", i + 1, "########################");
    
    The %.*s uses 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 15:22:31