【问题标题】:implicit declaration of function [-Wimplicit-function-declaration]函数的隐式声明 [-Wimplicit-function-declaration]
【发布时间】:2020-06-25 07:32:55
【问题描述】:

我是 C 编程的新手,我正在编写一个 C 程序,以使用单个函数查找学生在三门科目中获得的平均分数和百分比。我的代码是:

#include <stdio.h>
int main()
{
    float aver, per, mark1, mark2, mark3;
    printf("Enter the marks of subject 1: ");
    scanf(" %f", &mark1);
    printf("Enter the marks of subject 2: ");
    scanf(" %f", &mark2);
    printf("Enter the marks of subject 3: ");
    scanf(" %f", &mark3);
    averper(mark1, mark2, mark3, &aver, &per);
    printf("The average of marks entered by you = %f\n", aver);
    printf("The percentage of marks entered by you = %f", per);
    return 0;
}
float averper(float a, float b, float c, float *d, float *e)
{
    float sum = a + b + c;
    *d = sum / 3;
    *e = (sum / 300) * 100;
}

得到的错误是:

main.c:在函数“main”中: main.c:11:2:警告:函数“averper”的隐式声明 [-Wimplicit-function-declaration] averper(mark1, mark2, mark3, &aver, &per); ^~~~~~~ main.c:在顶层: main.c:16:7:错误:“averper”的类型冲突 float averper(float a, float b, float c, float *d, float *e) ^~~~~~~ main.c:11:2:注意:先前隐含的“averper”声明在这里 averper(mark1, mark2, mark3, &aver, &per); ^~~~~~~

谢谢

【问题讨论】:

  • 请关闭您的 CAPS LOCK。在线,全部大写 = 大喊大叫。你不想对你寻求帮助的人大喊大叫。 :-) (这次我已经为你删除了。)
  • 您需要在使用它们之前声明函数。
  • averper 中缺少返回
  • 您可以在此处查看:stackoverflow.com/questions/8440816/…。来自 C++,令人惊讶的是 C 只是隐式声明了一个未声明的函数。 (帖子之前被标记为 C++)

标签: c


【解决方案1】:

程序中的缺陷:

  1. 在定义函数签名之前使用函数或直接在代码顶部函数。

  2. 该函数不返回任何内容,如果程序设计为返回,但该值在任何地方都没有使用。


试试这个方法:

#include <stdio.h>

typedef struct { // declaring a struct to return avg and per together
    float avg;
    float per;
} averS;

averS averper(float, float, float, float *, float *); // function signature

int main()
{
    float aver, per, mark1, mark2, mark3;

    printf("Enter the marks of subject 1: ");
    scanf(" %f", &mark1);

    printf("Enter the marks of subject 2: ");
    scanf(" %f", &mark2);

    printf("Enter the marks of subject 3: ");
    scanf(" %f", &mark3);

    averS s = averper(mark1, mark2, mark3, &aver, &per); // holding values

    printf("The average of marks entered by you = %f\n", s.avg);
    printf("The percentage of marks entered by you = %f", s.per);

    return 0;
}

averS averper(float a, float b, float c, float *d, float *e)
{
    averS as; // declaring a local structure for returning value purpose.

    float sum = a + b + c;

    as.avg = sum / 3;
    as.per = (sum / 300) * 100;

    return as; // returning the struct
}

这里我们使用了struct,它保存两个值并将它们一起返回,然后它们在main()中使用。


编译成功后会输出如下内容:

Enter the marks of subject 1: 10 // --- INPUT
Enter the marks of subject 2: 20
Enter the marks of subject 3: 30
The average of marks entered by you = 20.000000 // --- OUTPUT
The percentage of marks entered by you = 20.000000

【讨论】:

    猜你喜欢
    • 2016-04-23
    • 1970-01-01
    • 2015-12-18
    • 1970-01-01
    • 1970-01-01
    • 2019-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多