为什么我的程序中不断出现“未定义的引用”错误?

时间:2019-03-01 23:43:26

标签: c

我是c的新手,对于我的作业,我们必须计算使用一个功能收取的费用。但是,每当我尝试调用该函数时,都会不断收到“对“ Calculate_charge”的未定义引用”。我在这到底是怎么了?

#include <stdio.h>

double Calculate_charge(double y);

int main(void)
{

    int customer;
    double charge = 0;
    int kwh;
    double totalcharge;
    int totalkwh;
    int totalcustomer;
    unsigned int count;

    customer = 0;
    kwh= 0;
    totalcharge = 0;
    totalkwh = 0;
    totalcustomer = 0;
    count = 0;

    printf( "%s","Enter customer number (-1 to quit):\n");
    scanf("%d", &customer);
    printf("%s", "Enter kwh used (-1 to quit):\n");
    scanf("%d", &kwh);

    while (customer != -1 && kwh != -1) {
        Calculate_charge(charge);
        printf( "Customer Num: %d\n", customer);
        printf("KWH used: %d\n", kwh);
        printf("Charge: %.2f\n", charge);
        count++;
        totalcustomer++;
        totalcharge = totalcharge + charge;
        totalkwh = totalkwh + kwh;

        printf( "%s","Enter customer number (-1 to quit):\n");
        scanf("%d", &customer);
        printf("%s", "Enter kwh used (-1 to quit):\n");
        scanf("%d", &kwh);  
        }

    double Calculate_charge(double y)
    {
        if (kwh <= 300) {
            y = .09 * kwh;  
        }
        else if (kwh > 300 &&  kwh <= 600){
            y = .08 * kwh;
        }
        else if (kwh > 600 && kwh <= 1000){
            y = .06 *kwh;
        }
        else {
            y = .05 * kwh;
        }
        return y;
    }

    if (count != 0) {

        printf("\n");
        printf("Total customers:%d\n", totalcustomer);
        printf("Total KWH used: %d\n", totalkwh);
        printf("Total Charged: %.2f" , totalcharge);
    }
}

1 个答案:

答案 0 :(得分:1)

您正在使用该函数,然后对其进行声明。向前声明它,然后在main()之前声明它。

您在代码中所做的事情是先声明它,然后在main() 中声明它,这不是该代码的正确位置。

它应该在主要功能的外部

最简单的解决方法是消除前向声明,而在此处声明函数:

#include <stdio.h>

double Calculate_charge(double y)
{
    if (kwh <= 300) {
        y = .09 * kwh;  
    }
    else if (kwh > 300 &&  kwh <= 600){
        y = .08 * kwh;
    }
    else if (kwh > 600 && kwh <= 1000){
        y = .06 *kwh;
    }
    else {
        y = .05 * kwh;
    }
    return y;
}

int main() {
  // ...

  return 0;
}