加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C将int值传递给float参数

发布时间:2020-12-16 10:43:42 所属栏目:百科 来源:网络整理
导读:这是我的代码片段: float square_root(x)float x;{ .......}int main(){ printf("Square_root 2 = %fn",square_root(4));} 当我将数字4.0传递给square_root()函数时,函数内部的x参数是4.0000000所以它的确定. 但是当我传递4(如例子)时,函数内的x变量变为1.
这是我的代码片段:

float square_root(x)
float x;
{
 .......
}

int main(){
    printf("Square_root 2 = %fn",square_root(4));
}

当我将数字4.0传递给square_root()函数时,函数内部的x参数是4.0000000所以它的确定.
但是当我传递4(如例子)时,函数内的x变量变为1.976262583365e-323#DEN

为什么会这样?

解决方法

您正在使用旧式的函数声明,其中参数类型单独列出.见 C function syntax,parameter types declared after parameter list

在传递int时,默认情况下它不会转换为float.但是,您的函数将参数解释为float,这会产生不良结果.

现代方法是在函数声明中包含参数类型,这将允许int参数自动转换为float.

float square_root(float x)
{
     .......
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读