无论您在发布的代码中做什么,您都没有double
在函数中使用数据类型。从函数返回类型来看,您似乎永远不会看到返回值 >127。
这段代码突出了一些问题:(这只是说明性的)
char hexRepresentation(double n){
if(n > 9){//comparing (double>int). Bad.
if(n==10) return 'A';
if(n==11) return 'B';
if(n==12) return 'C';//You wrote if(double == int). Bad.
if(n==13) return 'D';
if(n==14) return 'E';
if(n==15) return 'F';
}
return (char)n; //again unsafe downgrade from 8 bytes double to 1 byte char.
}
即使您修复了编译器错误,由于函数中数据类型的这种危险使用,您也可能无法始终获得所需的结果。
要知道它为什么不好,请看这里:
http://www.cygnus-software.com/papers/comparingfloats/Comparing%20floating%20point%20numbers.htm
我会在该函数体中使用fabs(n)
而不是任何地方。n
hexRepresentation
如果在此函数定义之前存在同名函数的先前声明或定义,则会显示错误“'hexRepresentation' 的类型冲突” 。此外,如果您没有声明一个函数并且它仅在被调用后出现,则int
编译器会自动假定它是。
因此,在 main() 之前声明和定义您的函数或在 main() 之前声明并在文件中的任何其他位置定义函数,但是使用相同的函数原型。
做:
char hexRepresentation(double); //Declaration before main
main()
{
...
}
char hexRepresentation(double n){//Definition after main
...
}
或者
char hexRepresentation(double n){ //Declaration and definition before main
...
}
main()
{
...
}