簡體   English   中英

function [-Wimplicit-function-declaration] 的隱式聲明

[英]implicit declaration of function [-Wimplicit-function-declaration]

我是 C 編程的新手,我正在制作一個 C 程序,以查找學生使用單個 ZC1C425268E68385D1AB5074C17A94F14 在三個科目中獲得的分數的平均值和百分比。 我的代碼是:

#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: In function ‘main’:
main.c:11:2: warning: implicit declaration of function ‘averper’ [-Wimplicit-function-declaration]
  averper(mark1, mark2, mark3, &aver, &per);
  ^~~~~~~
main.c: At top level:
main.c:16:7: error: conflicting types for ‘averper’
 float averper(float a, float b, float c, float *d, float *e)
       ^~~~~~~
main.c:11:2: note: previous implicit declaration of ‘averper’ was here
  averper(mark1, mark2, mark3, &aver, &per);
  ^~~~~~~ 

謝謝

程序中的缺陷:

  1. 在定義 function 簽名之前使用 function 或在代碼頂部直接使用 function。

  2. function 不返回任何內容,如果程序設計為返回,但該值無處使用。


試試這個方法:

#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()中使用它們。


編譯成功后會出現 output 類似:

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

這是否僅適用於 C99 或更高版本?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM