首页 > 解决方案 > 如何在 C 中使用自定义库

问题描述

我已经编写了一些关于 uni 分配的代码,但我一直在遇到这样的问题,即我的自定义函数没有提供任何其他输出然后为零。

基本上,我在问如何检索要在我的代码中使用的函数的结果。

在这里,我将粘贴我的代码。

    #include <stdio.h>

    //math.h is included via the header file because the compiler liked it better.

    int V;

    int H;

    int R;

    int result;

    #include "A1_header.h"

    int main()
    {

    //small introduction
    printf("Welcome to the volume test game\n");
    printf("We will start with spheres. \n");
    printf("Please input your sphere radius here:");
    scanf("%d", &R);
    CalcSphVolume(&V, &R);
    printf("please input your result:");
    scanf("%d", &result);
    if(result == V){
        printf("Congratulations, your answer is correct!\n");
    }
    else{
        printf("Wrong answer, the correct result was %d \n", V);
    }
    return 0;
}

下面是我用来定义函数的 .h 文件。

    #ifndef Point

    #define Point

    #include <math.h>

    //these are the functions for Sphere calculations

    void CalcSphVolume(int V, int R) {
    V = 1.33*3.14(R*R*R);
    }

    void CalcSphRadius(int V, int R) {
    R = cbrt(V/4.1762);
    return;
    }

    //these are the functions for the Cone calculations

    void CalcConVolume(int V, int R, int H) {
    V = 0.33*(3.14*(R*R))H;
    return;
    }

    void CalcConHeight(int V, int R, int H) {
    H = V/(0.33*(3.14*(R*R)));
    } 

    void CalcConRadius(int V, int R, int H) {
    R = sqrt(V/(0.33*3.14H));
    }

    //these are the functions for the Cilinder calculations

    void CalcCilVolume(int V, int R, int H) {
    V = 3.14*H*(R*R);
    }

    void CalcCilHeight(int V, int R, int H) {
    H = V/(3.14(R*R));
    }

    void CalcCilRadius(int V, int R, int H) {
    R = sqrt(V/(3.14*H));
    }

    #endif

标签: cshared-libraries

解决方案


问题是您的函数参数采用整数而不是指向内存地址的指针。

你想要做的是:

 void CalcSphRadius(int *V, int *R) 
 {
     *R = cbrt((*V)/4.1762);
     return;
 }

现在,该函数正在接收指向 V 和 R 的指针,并将读取/写入它们的内存地址。

如上所示,不要忘记使用星号“*”取消对指针的引用,这样您就可以写入存储在这些地址中的值,而不仅仅是进行指针运算。

您还可以使用函数的返回类型来检索值。

 int CalcSphRadius(int V) 
 {
     return cbrt(V/4.1762);
 }

然后使用它们来分配变量,如下所示:

R = CalcSphRadius(V);

推荐阅读