无论你在代码中做的贴出来,不使用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()
{
...
}
会是什么回报,如果你在5.6过去了?甚至10以下的整数值? '(char)5'不是'5'''。 – chris
除了有问题的决定让它接受'双',你在使用之前是否声明了这个函数?如果您来自Java,您可能已经忘记了这一点。 –
我现在甚至不关心这一点。我将n作为其他函数的双精度 - 特别是来自math.h的pow()。到目前为止,我只使用整数。 –