c - C中int类型的sqrt()

标签 c int double sqrt

我在 mac os x 上用 c 语言编程。我正在使用 math.h 中的 sqrt,函数如下:

int start = Data -> start_number;
double localSum;

for (start; start <= end; start++) {
    localSum += sqrt(start);
}

这行得通,但为什么呢?为什么我没有收到警告?在 sqrt 的手册页上,它采用 double 作为参数,但我给它一个 int - 它如何工作?

谢谢

最佳答案

不会导致精度损失的类型转换可能不会引发警告。它们是隐式转换的。

int --> double //no loss in precision (e.g 3 became 3.00)
double --> int //loss in precision (e.g. 3.01222 became 3)

什么触发警告,什么不触发警告,很大程度上取决于编译器和提供给它的标志,然而,大多数编译器(至少我用过的)不考虑隐式类型转换危险足以保证警告,因为它是语言规范中的一项功能。


警告或不警告:

C99 Rationale 将其表述为指南

One of the important outcomes of exploring this (implicit casting) problem is the understanding that high-quality compilers might do well to look for such questionable code and offer (optional) diagnostics, and that conscientious instructors might do well to warn programmers of the problems of implicit type conversions.

C99 Rationale (Apr 2003) : Page 45

关于c - C中int类型的sqrt(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13178618/

相关文章:

arrays - 如何将字符串拆分为 2 个数组 Swift 4

c - C 中的值是 double 的

C++ 多维双数组不能按预期工作

c - 显示随机生成的整数的频率

c - 分配实例化结构时出现段错误?

c - 事实与枚举

c - 当我将字符串分配给 int 时会发生什么?

ios - 如何在关闭应用程序后维护一个值(int 或 string)以供使用

c# - 为什么将 double.epsilon 添加到一个值会产生相同的值,完全相等?

C++ - cstyle 结构/类包装相关吗?