gpt4 book ai didi

C:数据类型。 sqrt 函数与 int 一起使用为什么?

转载 作者:行者123 更新时间:2023-11-30 15:27:15 24 4
gpt4 key购买 nike

我是 C 初学者,在 JavaScript 之后开始学习,无法适应这些类型。

好吧,math.h 的 sqrt 函数应该使用 double ,据我所知,在 C 中你不能将错误的类型作为参数传递。

但是当我去的时候:

int b = sqrt(1234); //it works

也是这样

float b = sqrt(1234); // it works
int b = sqrt(1234.22) // it works

为什么这些都有效?这里的流程是什么样的?

我的猜测是:无论我传递什么,sqrt的参数都会自动转换为double,如果我分配给的变量是 int 类型,则结果 double 会转换为 int。

那么两个问题?

1) 如果我传递了错误的类型,为什么其他函数会出现错误,而 sqrt 却不会?2) 如果我们可以像这样将 int 转换为 float

 float b = 123.44
int a = b;

为什么我们需要这个?

 float b = 123.44
int a = (int) b;

最佳答案

Why are all these [two initializations] work?

第一次初始化float b = sqrt(1234)之所以有效,是因为该语言“向上转换”了整数文字 1234double在调用sqrt之前,然后将结果转换为float .

第二次初始化int b = sqrt(1234.22)出于同样的原因,除了这次编译器不必向上转换 1234.22调用之前的文字,因为它已经是 double 类型.

这在 C99 标准中进行了讨论:

6.3.1.4.1: When a finite value of real floating type is converted to an integer type other than _Bool, the fractional part is discarded.

6.7.8.11: The initializer for a scalar shall be a single expression, optionally enclosed in braces. The initial value of the object is that of the expression (after conversion) (emphasis added).

-

why do we need this [cast int a = (int) b;]?

您可以插入强制转换以提高可读性,但标准并不要求它 ( demo )。

关于C:数据类型。 sqrt 函数与 int 一起使用为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27105695/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com