【问题标题】:Why this code got compile error in ANSI C?为什么这段代码在 ANSI C 中出现编译错误?
【发布时间】:2021-02-11 18:38:09
【问题描述】:

我正在一个名为 UVa Online Judge 的站点上解决一个基本的 C 问题,我遇到了一个似乎与编译器选项有关的错误。

ANSI C 5.3.0 - GNU C Compiler with options: -lm -lcrypt -O2 -pipe -ansi -DONLINE_JUDGE

问题(以问题 ID 作为前缀)是UVa 100 3n+1 problem,如下所示。它可以在 Visual Studio 2019 上无错误地编译和运行,该站点报告了“编译错误”。该站点不会显示任何错误消息,只会在其公告中显示Compile Error


#include <stdio.h>
int get_cycle_length(int n);

int main() {
    int i, j;
    int l, r;
    int max;
    int n;
    int cycle_length;
    char line[10000] = { 0 };
    size_t line_len = sizeof(line), read_len = 0, pos = 0;
    while (scanf(" %d%d", &i, &j) != EOF) {
        l = i > j? j: i;
        r = i > j? i: j;
        max = -1;
        for (n = l; n <= r; n++) {
            cycle_length = get_cycle_length(n);
            if (cycle_length > max)
                max = cycle_length;
        }

        read_len = snprintf(line+pos, line_len-pos, "%d %d %d\n", i, j, max);
        if (pos+read_len > line_len) {
            printf("%.*s", (int)pos, line);
            pos = 0;
        }
        pos += read_len;

        // printf("%d %d %d\n", i, j, max);
    }
    printf("%.*s", (int)pos, line);
    return 0;
}

int get_cycle_length(int n) {
    int count = 0;
    while (n != 1) {
        count++;
        n = n & 1? 3*n+1: n/2;
    }
    count++;
    return count;
}

【问题讨论】:

  • 什么是错误?
  • @VladfromMoscow:我用的是VS2019,没有报错,但是提交后只显示CE。
  • 乍一看我会怀疑这一行:` char line[10000] = { 0 }; `
  • @Devolus:我尝试将其移至全局并省略 = { 0 },仍然获得 CE。
  • 尝试用/* ... */替换//评论。

标签: c visual-studio-2019 ansi-c


【解决方案1】:

您在代码中使用 C++ 样式的 cmets,即 //

许多 C 编译器将允许这些类型的 cmets 作为扩展,但严格的 ANSI C 不允许。您需要使用 C 风格的 cmets /* ... */

所以不要这样:

// printf("%d %d %d\n", i, j, max);

这样做:

/*
printf("%d %d %d\n", i, j, max);
*/

【讨论】:

  • 大声笑,我认为是(并且已经尝试过)size_t 或本地 char line[],缺少 #include&lt;...&gt;(因为 IDE 总是帮我太多......,即自动包含幕后)。
猜你喜欢
  • 2011-12-27
  • 2012-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-28
  • 2023-03-27
  • 2015-10-30
相关资源
最近更新 更多