不同数据类型的函数调用
这个程序的第7行不是“pay = prt(pay);”应该抛出编译或运行时错误,因为它将 int 传递给需要 double 的参数?我用 dev-c++ 很好地编译了它,并用两行输出运行了程序。请解释一下,谢谢。
#include <stdio.h>
int prt(double b);
main ()
{
int pay = 3;
double tax = 2.2;
pay = prt(pay);
prt(tax);
}
int prt(double b)
{
b *= 2;
printf("%.2lf\n", b);
}
Isn't line 7 of this program "pay = prt(pay);" supposed to throw a compile or run-time error because it is passing in an int to a param that requires a double? I compiled it fine with dev-c++ and ran the program with both lines of output. Please explain, thank you.
#include <stdio.h>
int prt(double b);
main ()
{
int pay = 3;
double tax = 2.2;
pay = prt(pay);
prt(tax);
}
int prt(double b)
{
b *= 2;
printf("%.2lf\n", b);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在这种情况下,C 会自动在不同的数字类型之间进行转换。
请参阅类 C 语言中的隐式类型转换。
C will automatically convert between different numeric types in this situation.
See Implicit type conversion in C-like languages.
您将函数声明为
int
但从未返回任何内容,也没有为main
提供返回类型。我想说任何编译器都有权拒绝你的代码。You declared a function as
int
but never returned anything, and didn't givemain
a return type either. I'd say any compiler would be well within it's rights to reject your code.具有较小或相同大小的数据类型可以转换为较大的数据类型。
相反的情况:
float 到 int 会导致截断,即删除小数部分。
double 到 float 会导致数字四舍五入
long int 到 int 会导致丢弃多余的高阶位。
data type having smaller or equal size can be converted to higher one.
in reverse case:
Float to int causes truncation, ie removal of the fractional part.
double to float causes rounding of digit
long int to int causes dropping of excess higher order bits.