一个函数定义的返回值是float,它不能在return语句中返回的值的类型是?
A. char B. int C. float D.long E. double F.以上皆可以
“函数有返回值时,系统首先会自动隐式地将返回表达式的值的类型转换为函数的返回类型,然后再赋值给调用函数返回;”
这里涉及到类型转换(自动类型转换、隐式类型转换)问题。
先写个代码,看看程序运行情况:
#include<stdio.h>
float test(int x)
{
char c='a';
int i=10;
float f=10.0f;
long l=1000;
double d=10.0;
switch(x)
{
case 1:
return c;
case 2:
return i;
case 3:
return f;
case 4:
return l;
case 5:
return d;
}
}
void main()
{
float f;
int i=0;
for(i=1;i<=5;i++)
{
f=test(i);
printf("%f\n",f);
}
}
运行结果:
97.000000
10.000000
10.000000
1000.000000
10.000000
请按任意键继续. . .
程序可以正常运行,但是会出现一些警告:
警告 1 warning C4244: “return”: 从“int”转换到“float”,可能丢失数据
警告 2 warning C4244: “return”: 从“long”转换到“float”,可能丢失数据
警告 3 warning C4244: “return”: 从“double”转换到“float”,可能丢失数据
警告 4 warning C4715: “test”: 不是所有的控件路径都返回值