【问题标题】:I got: "expected ';', ',' or ')' before '&' token "in C [closed]我得到:“预期的';',','或')'之前'&'令牌“在C [关闭]
【发布时间】:2021-09-05 09:37:02
【问题描述】:

为什么&x1不能被接受

int calculte (float a, float b, float c, float &x1, float &x2)

我正在尝试求解二次方程,这是我的完整程序


    #include<stdio.h>
    #include<math.h>
    int calculte  (float a, float b, float c, float &x1, float &x2){
        float delta = b*b -4*a*c;
        if (delta <0) {
            x1 =x2 = 0.0;
            return 0;
        } if (delta == 0) {
            x1 = x2 = -b/(2*a);
            return 1;
        } if (delta >0) {
            delta = sqrt(delta);
            x1 = (-b-delta)/(2*a);
            x2 = (-b - delta)/(2*a);
            return 2;
        }
    }
    int main () {
        float a, b, c, x1, x2;
        do {
            scanf ("%f %f %f", &a, &b, &c);
        }
        while (!a);
        int ans = calculte (a,b,c,x1,x2);
        if (ans==0) {
            printf ("NO");
        } 
        if (ans==1){
            printf ("%.2f",x1);
        }
        if (ans==2) {
            printf ("%.2f %.2f", x1, x2);
        }
    }

我是编程新手,所以希望你们能详细解释一下。

【问题讨论】:

  • c 不支持引用调用。
  • @thaison_h 在 C 中这个符号 & 不能用在声明符中。
  • “我需要一些有关此代码的帮助”不是问题!究竟是什么问题?

标签: c gcc-warning


【解决方案1】:

您不能在 C 中使用引用。

您应该通过将&amp; 更改为* 来将参数指向指针。

函数体和调用也必须据此更改。

#include<stdio.h>
#include<math.h>
int calculte  (float a, float b, float c, float *x1, float *x2){ /* change the arguments to pointers */
    float delta = b*b -4*a*c;
    if (delta <0) {
        *x1 =*x2 = 0.0; /* dereference the pointers */
        return 0;
    } if (delta == 0) {
        *x1 = *x2 = -b/(2*a); /* dereference the pointers */
        return 1;
    } if (delta >0) {
        delta = sqrt(delta);
        *x1 = (-b-delta)/(2*a); /* dereference the pointer */
        *x2 = (-b - delta)/(2*a); /* dereference the pointer */
        return 2;
    }
}
int main () {
    float a, b, c, x1, x2;
    do {
        scanf ("%f %f %f", &a, &b, &c);
    }
    while (!a);
    int ans = calculte (a,b,c,&x1,&x2); /* add & to get the pointers */
    if (ans==0) {
        printf ("NO");
    } 
    if (ans==1){
        printf ("%.2f",x1);
    }
    if (ans==2) {
        printf ("%.2f %.2f", x1, x2);
    }
}

【讨论】:

    猜你喜欢
    • 2017-10-28
    • 2023-03-31
    • 2014-11-10
    • 1970-01-01
    • 2012-10-30
    • 1970-01-01
    • 2013-11-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多