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