sách gpt4 ai đã đi

Giới thiệu về C - Làm thế nào để truyền tham số theo tham chiếu trong một hàm?

In lại 作者:行者123 更新时间:2023-12-04 12:12:26 26 4
mua khóa gpt4 Nike

我正在做我的介绍 C 类(class)作业,我的任务是执行以下任务......

  • 为一个函数编写代码,该函数通过值接收两个参数(a 和 b)并通过引用具有另外两个参数(c 和 d)。所有参数都是双倍的。
  • 在 main 中,使用 scanf 获取两个数字,然后调用该函数,然后在 printf 语句中将两个返回值显示到输出中。
  • 该函数通过将 (a/b) 分配给 c 并将 (a*b) 分配给 d 来工作。

  • 虽然我的知识很基础,但我相信我了解要点
    在主要
          //first and second double hold the scanf inputs
    double first;
    double second;

    //unsure here - to reference c and d as parameters in the function, do I simply declare unfilled double variables here?
    double *c;
    double *d;

    printf("Enter your first number\n");
    scanf("%f\n", &first);
    printf("Enter your second number\n");
    scanf("%d\n", &second);

    //call the function, first and second by value, &c / &d by reference - correct?
    pointerIntro(first, second, &c, &d);

    对于函数...
    float myFunction(double a, double b, double *c, double *d)
    {
    c = a/b;
    d = a*b;


    //printf statements
    }

    如果这个问题的流程很困惑,我很抱歉,但它对我来说是过程的一部分:P

    所以,对于我的正式问题
    1.在main中启动两个双指针变量(*c和*d)作为函数中的引用传递是否正确?
    2. 我可以通过说 &c/&d 来调用带有引用指针的函数吗?
    3. 对这个提问还有其他批评吗?

    1 Câu trả lời

    变量 'c' 和 'd' 不必是通过引用传递它们的指针。所以你有两种情况:

  • 当你在主函数中定义'c'和'd'作为指针时,你会将它们传递给函数,如下所示:pointerIntro(first, second, c, d);因为它们已经是指针,你不需要发送它们的引用,你只需发送它们。
  • 如果将'c' 和'd' 定义为双变量double c, d;您将使用这样的“&”符号通过引用将它们发送到函数:pointerIntro(first, second, &c, &d); .

  • 然后在你的函数中实际设置'c'和'd'的值,你需要像这样取消引用指向它们的指针: *c = a/b; *d = a*b; .

    如果您不熟悉,可以在此处查看取消引用指针的含义: What does "dereferencing" a pointer mean?

    应该工作的代码:
    #include 

    void myFunction(double a, double b, double *c, double *d)
    {
    *c = a / b;
    *d = a * b;
    }

    int main(void)
    {
    double a, b, c, d;

    scanf("%lf", &a);
    scanf("%lf", &b);

    myFunction(a, b, &c, &d);

    printf("%lf %lf", c, d);
    }

    关于C 介绍 - 如何在函数中通过引用传递参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58888981/

    26 4 0
    Bài viết được đề xuất: r - 在数据框的列上进行 Strsplit
    Bài viết được đề xuất: r - 使用用户定义的函数在 r 中应用
    Bài viết được đề xuất: api - 网络音频 API WaveShaperNode
    Bài viết được đề xuất: r - 将来自以下 ID 的字符串与当前 ID 中的字符串组合
    行者123
    Hồ sơ cá nhân

    Tôi là một lập trình viên xuất sắc, rất giỏi!

    Nhận phiếu giảm giá Didi Taxi miễn phí
    Mã giảm giá Didi Taxi
    Giấy chứng nhận ICP Bắc Kinh số 000000
    Hợp tác quảng cáo: 1813099741@qq.com 6ren.com