【问题标题】:square of a float number in CC中浮点数的平方
【发布时间】:2011-12-10 02:46:04
【问题描述】:

我用 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

【问题讨论】:

    标签: c floating-point floating-point-conversion


    【解决方案1】:

    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“有效”,您必须向我们展示您用于该案例的确切代码。

    【讨论】:

    • C 在调用尚未声明的函数时会做一些特别的事情。它假设参数和返回类型是int 什么的,我记不清了。
    • 是的,我知道这一点。但我不确定确切的行为,因为我从不使用该功能......同样适用于函数内部的函数 - 这是我避免的一个领域。
    • 感谢这两个答案都有效,如果我们没有声明 type ,我认为 C 采用“int”。我想的是真的吗?
    • 是的,C 确实在未指定类型时采用默认 int。但是,这是折旧的,建议始终指定类型。所以我的猜测是默认的int 允许您的初始案例工作。
    【解决方案2】:

    您只是缺少您提供的原型中的参数。你有

    float square();
    

    应该是什么时候

    float square(float);
    

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

    【讨论】:

    • 有趣,我不知道您可以将声明留在函数中。 +1
    • @Mysticial 这就是烦人的地方,你不能对一个变量进行值初始化(或者它是默认初始化?),其构造函数不带参数:MyClass m; 有效,但 MyClass m(); 无效因为它是一个函数原型。 (内置类型也一样。)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多