3

我用 C 语言编写了一个代码,它适用于 int,但是当我尝试使用 float 执行此操作时,它显示错误我该怎么做才能使其正确。

#include<stdio.h>

int main()
{
    float a,y;
    float square();
    scanf("%f", &a);
    y = square( a );
    printf("%f %f ",a ,y);
}

float square(float b)
{
    float z;
    z = b*b;
    printf("%f %f",z ,b);
    return(z);
}

错误:

return.c:12: error: conflicting types for 'square'
return.c:13: note: an argument type that has a default promotion can't match an empty parameter name list declaration
return.c:6: note: previous declaration of 'square' was here
4

2 回答 2

8

将声明square()移出函数并确保原型匹配:

float square(float b);  //  Make sure this matches the definition.

int main()
{
    float a,y;
    scanf("%f", &a);
    y = square( a );
    printf("%f %f ",a ,y);
}

float square(float b)
{
    float z;
    z = b*b;
    printf("%f %f",z ,b);
    return(z);
}

至于为什么它“有效” int,您必须向我们展示您用于该案例的确切代码。

于 2011-12-10T02:47:17.067 回答
4

你只是错过了你给出的原型中的论点。你有过

float square();

什么时候应该

float square(float);

您不需要将其移到函数之外,但您需要确保原型与您稍后定义的函数具有相同的签名(返回类型、名称和参数计数/类型)。

于 2011-12-10T02:55:54.043 回答