You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

C语言报错:operators未声明(函数内首次使用)求助

问题分析与修复

嘿,我一眼就看到了问题所在——你把结构体的类型名和变量名搞混了,这也是新手写C结构体时很容易犯的错。咱们一步步拆解你的问题,然后把代码修好:

核心错误:混淆结构体类型与变量

你定义了struct operators作为结构体类型,然后在main里声明了一个该类型的数组变量calc

struct operators calc[4] = { ... };

但后续代码里你却直接用operators(类型名)去访问元素,比如operators[i]operators.symbol——编译器根本找不到名为operators的变量,这就是你收到operators undeclared报错的原因。所有这类写法都要替换成你的数组变量名calc

其他需要修复的问题

除了核心错误,代码里还有几个语法和逻辑问题:

  • scanf格式字符串错误scanf("%i || &c", ...)完全不符合语法,如果你想读取数字或符号,需要拆分逻辑,或者用正确的格式符(比如%d %c),同时要单独声明变量存储输入的符号。
  • 数组索引逻辑错误opNum || operators.symbol是逻辑或运算,结果只能是0或1,根本无法正确定位到你想要的运算符元素。你需要遍历数组,匹配用户输入的索引或符号。
  • 未声明变量op1op2没有定义,需要先声明并初始化这两个操作数。
  • printf格式符不匹配:输出时operators.symbol是char类型,应该用%c格式符,而不是%s

修正后的完整代码

#include<stdio.h>
#include <stdlib.h>
#include <time.h> // 用于初始化随机数种子
#include "input.h"
#include "operations.h"

typedef int (*arithmeticFcn)(int, int);

struct operators {
    char symbol;
    char opName[10];
    arithmeticFcn fcn;
};

int main() {
    int opNum, res, op1 = 10, op2 = 5; // 初始化操作数op1、op2
    char inputSymbol;
    struct operators calc[4] = {
        {'+', "Add", addition},
        {'-', "Subtract", subtract},
        {'*', "Multiply", multiply},
        {'/', "Divide", divide}
    };

    // 初始化随机数种子,保证每次打乱结果不同
    srand(time(NULL));

    // 打乱运算符数组
    for(int i=0; i<4; i++) {
        int j= rand() % 4;
        struct operators temp = calc[i];
        calc[i] = calc[j];
        calc[j] = temp;
        // 修正输出:使用变量calc,匹配正确的格式符
        printf("%d or %c: %s\n", i, calc[i].symbol, calc[i].opName);
    }

    printf("Enter Hotkey (number) or Operator Symbol: ");
    // 处理用户输入,支持数字索引或运算符符号
    if (scanf("%d", &opNum) == 1) {
        // 用户输入了数字索引,先检查合法性
        if (opNum >=0 && opNum <4) {
            res = calc[opNum].fcn(op1, op2);
            printf("%d %c %d = %d\n", op1, calc[opNum].symbol, op2, res);
        } else {
            printf("Invalid number!\n");
        }
    } else {
        // 清空输入缓冲区,读取符号
        while(getchar() != '\n');
        scanf("%c", &inputSymbol);
        // 遍历数组匹配符号
        int found = 0;
        for(int i=0; i<4; i++) {
            if (calc[i].symbol == inputSymbol) {
                res = calc[i].fcn(op1, op2);
                printf("%d %c %d = %d\n", op1, calc[i].symbol, op2, res);
                found = 1;
                break;
            }
        }
        if (!found) {
            printf("Invalid operator symbol!\n");
        }
    }

    return 0;
}

额外说明

  • 我加了#include <time.h>并调用srand(time(NULL)),这样每次运行程序时随机打乱的结果才会不一样。
  • 修正了用户输入的处理逻辑,现在可以支持输入数字索引或者运算符符号,同时增加了合法性检查,避免数组越界或无效输入。

内容的提问来源于stack exchange,提问作者Justin Macwan

火山引擎 最新活动