我想知道为什么编译器让这个通过并给出正确的输出,尽管sqrt()从它的原型通常应该只得到一个double值作为参数:
在 C99 中,原型的声明是:
双sqrt(双x);
#include <stdio.h>
#include <math.h>
int main (void)
{
int i = 9;
printf("\t Number \t\t Square Root of Number\n\n");
printf("\t %d \t\t\t %f \n",i, sqrt(i));
}
Run Code Online (Sandbox Code Playgroud)
输出:
#include <stdio.h>
#include <math.h>
int main (void)
{
int i = 9;
printf("\t Number \t\t Square Root of Number\n\n");
printf("\t %d \t\t\t %f \n",i, sqrt(i));
}
Run Code Online (Sandbox Code Playgroud)
如果我给sqrt()函数一个intas 参数,为什么编译器至少不抛出警告并且给定的输出是正确的?
这是进入未定义行为吗?
我正在使用 gcc。
这个问题已经针对 C++ 提出了两次,但没有针对 C,所以我的问题是针对 C 的。无论如何,我提供了 C++ 问题的链接:
我正在从文本中学习C. 作者提供的示例代码是:
#include <math.h>
main()
{ int i;
printf("\t Number \t\t Square Root of Number\n\n");
for (i=0; i<=360; ++i)
printf("\t %d \t\t\t %d \n",i, sqrt((double) i));
}
Run Code Online (Sandbox Code Playgroud)
在我的电脑上产生不正确的输出,我不明白:
Number Square Root of Number
0 259
1 515
2 771
3 1027
4 1283
5 1539
6 1795
7 2051
8 2307
9 2563
10 2819
11 3075
12 3331
13 3587
14 3843
15 4099
16 4355
17 4611
18 4867
19 5123
20 5379
21 5635
22 5891
23 …Run Code Online (Sandbox Code Playgroud)