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

C语言数组定义报错求助:解决Expected identifier or '{'及declaration of anonymous struct must be a definition问题

C语言数组定义报错求助:解决Expected identifier or '{'及declaration of anonymous struct must be a definition问题

兄弟,我看了你贴的代码,这一堆报错都是基础语法没捋顺导致的,咱们一个个拆解解决:

首先先把你遇到的两个核心报错的根源说透:

  • 你写的struct coolarray[4];完全是错误语法,你想定义存分数的数组根本不需要加struct关键字,这个写法会被编译器当成“匿名结构体声明”,所以才会跳出declaration of anonymous struct must be a definition的报错。
  • 除此之外代码里还有一堆细节语法错误,比如赋值用了比较运算符、函数调用用错括号、数组索引计算逻辑混乱、printf调用不规范等等,这些都会触发各种编译报错。

接下来我把你的代码完全修正,再给你逐个解释问题点:

修正后的完整可运行代码

#include <stdio.h>
#include <cs50.h>

// 改成void类型,因为这个函数不需要返回值
void call_loop() {
    // 正确定义能存4个整数的数组,不需要struct关键字
    int coolarray[4];
    
    // 用=赋值(不是==比较运算符),函数调用用圆括号()而非大括号{}
    coolarray[0] = get_int("Test score 1: ");
    coolarray[1] = get_int("Test score 2: ");
    coolarray[2] = get_int("Test score 3: ");
    coolarray[3] = get_int("Test score 4: ");
    
    // 正确计算四个元素的总和,不是索引相加
    int total = coolarray[0] + coolarray[1] + coolarray[2] + coolarray[3];
    // 转成浮点型计算避免整数除法丢失精度,再计算百分比
    float average_percent = (float)total / 4 * 100;
    
    // printf必须带格式字符串,指定输出格式
    printf("Average percentage: %.2f%%\n", average_percent);
}

int main(void) {
    call_loop();
    printf("\n");
    return 0;
}

逐个拆解你代码里的错误点

  • 数组定义错误:struct coolarray[4];是完全错误的写法,定义整数数组直接写int coolarray[4];就行,struct是用来定义结构体类型的,和普通数组毫无关系,这是你第一个报错的核心原因。
  • 赋值运算符用错:你用了==(用来判断两个值是否相等),但变量赋值应该用=,这是新手最容易踩的坑。
  • 函数调用语法错误:get_int是CS50库的函数,调用必须用圆括号(),不是大括号{},正确写法是get_int("Test score 1: ")。
  • 数组索引计算逻辑错误:你写的coolarray[0 + 1 + 2 + 3]其实是在取coolarray[6],这已经超出数组的合法索引范围(数组索引是0-3),完全不是你要的“四个元素相加”,正确写法是把每个数组元素单独相加:coolarray[0] + coolarray[1] + coolarray[2] + coolarray[3]。
  • 整数除法精度丢失:如果直接用整数计算total/4,会因为整数除法直接丢弃小数部分(比如总分150,150/4会得到37而不是37.5),所以要先把total转成浮点型(float)total再计算,才能保留精度。
  • printf使用错误:printf(cadc);是错误的,printf必须先传入格式字符串,比如输出整数用printf("%d", cadc),输出浮点数用printf("%.2f", value),不然编译器不知道该如何解析这个变量。
  • 函数返回值和main函数结构错误:你的call_loop函数不需要返回值,应该定义成void call_loop()而不是int;main函数里你先执行return call_loop();,后面的printf("\n");根本不会被执行,而且return的位置完全不对,应该先调用call_loop,再return 0。
  • 多余的大括号:代码里嵌套了很多不必要的大括号(比如call_loop里的{ coolarray[0] == ... }),这些多余的大括号会让编译器误解代码结构,直接删掉就行。

按照上面的修正,你代码的所有报错都会解决,逻辑也能正常运行啦。

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.07 13:23:02