C++ 错误:一元“*”的无效类型参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22902985/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
error: invalid type argument of unary '*'
提问by user3502479
I don't understand these errors can someone explain?
我不明白这些错误有人可以解释吗?
error: invalid type argument of unary '' (have 'double') error: invalid type argument of unary '' (have 'double') error: invalid type argument of unary '*' (have 'double')
错误:一元' '的无效类型参数(有'double')错误:一元''的无效类型参数(有'double')错误:一元'*'的无效类型参数(有'double')
double getMedian(double *array, int *hours){
if (*hours <= 0) return 0;
if (*hours % 2) return (float)*array[(*hours + 1) / 2];
else{int pos = *hours / 2;
return (float)(*array[pos] + *array[pos + 1]) / 2;}}
回答by ppl
You are already dereferencing array
with the []
operator. What you want is:
您已经在取消array
对[]
运算符的引用。你想要的是:
double getMedian(double *array, int *hours){
if (*hours <= 0) return 0;
if (*hours % 2) return (float)array[(*hours + 1) / 2];
else{int pos = *hours / 2;
return (float)(array[pos] + array[pos + 1]) / 2;}}
Note that writing x[y]
is shorthand for *(x + (y))
. In your code, you have essentially have the equivalent of **array
.
请注意,写作x[y]
是 的简写*(x + (y))
。在您的代码中,您基本上拥有相当于**array
.
回答by sajas
When you use the [] operator on the arrays or pointers, you don't have to dereference them again to get the value. you could just say,
当您在数组或指针上使用 [] 运算符时,您不必再次取消引用它们来获取值。你只能说,
if (*hours % 2) return (float)array[(*hours + 1) / 2];
and
和
return (float)(array[pos] + (array[pos + 1]) / 2);
回答by John3136
*array[(*hours + 1) / 2];
so array
is an array of doubles. You treating it as a 2D array because you try to dereference once via *
and one via []
.
*array[(*hours + 1) / 2];
array
双打数组也是如此。您将其视为二维数组,因为您尝试取消引用一次 via*
和一次 via []
。
Also, I'd add some ()
to all of that to make it a bit clearer without having to memorise the order of operations.
此外,我会()
在所有这些内容中添加一些内容,以便在不必记住操作顺序的情况下更清晰一些。