C中的浮点数的平方

时间:2022-09-28 07:21:30

I have written a code in C which works fine for int but when I try to do this with float it is showing error what can i do to make it correct.

我用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);
}

error:

错误:

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

2 个解决方案

#1


8  

Move the declaration of square() out of the function and make sure the prototype matches:

将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);
}

As for why it "worked" for int, you'll have to show us the exact code you used for that case.

至于为什么它对int“起作用”,您将必须向我们展示您在这种情况下使用的确切代码。

#2


4  

You're just missing the argument in the prototype you gave. You had

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

float square();

When it should be

当它应该

float square(float);

You don't need to move it outside the function, but you do need to make sure the prototype has the same signature (return type, name, and parameter count/types) as the function that you define later.

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

#1


8  

Move the declaration of square() out of the function and make sure the prototype matches:

将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);
}

As for why it "worked" for int, you'll have to show us the exact code you used for that case.

至于为什么它对int“起作用”,您将必须向我们展示您在这种情况下使用的确切代码。

#2


4  

You're just missing the argument in the prototype you gave. You had

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

float square();

When it should be

当它应该

float square(float);

You don't need to move it outside the function, but you do need to make sure the prototype has the same signature (return type, name, and parameter count/types) as the function that you define later.

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