Error: invalid operands of types 'int' and 'float*' to binary'operator/'
int *average = new int((num) / data);
显示这行代码。 为什么这样?
float *data;
int num;
int mode;
double average, median;
cout << "How many students were surveyed? ";
cin >> num;
data = makeArray(num);
float getAverage(float *data, int num)
{
int *average = new int((data) / num);
return *average;
}
答案 0 :(得分:1)
这意味着您要将两种不兼容的类型进行比较。 num
和data
中的一个是int
,另一个是float*
。根据您想要的行为
*x
中指针的任何x
一样
2A。您需要将int
转换为float
floating point division
,其结果将转换回int
float
转换为int
,integer division
,然后转换回int
。 <强>更新强>
由于您更新了代码,我将指出一个更大的问题;你现在正在泄露记忆。
我建议你考虑通过值返回你的整数,并可能通过引用或常量引用传递并完全避免指针,但更多的我会建议输入参数中的一些对称性以及const正确性:
//your code:
float getAverage( float *data, int sum )
{
//data is a float* and needs to be de-ref'd and casted to int for float but isnt
int *average = new int( (data) / num );
//note that now average is a pointer to a newly constructed int that will never be free'd
return *average; //because you return it here, where the value will then be implicily converted to a float and be mostly worthless.
}
// In both suggestions I will use symmetric types, I will not introduce dynamic memory and I will use floating point division for maximal accuracy.
// Suggestion one use Const References
float getAverage( const float &data, const int &num)
{
float result = data / (float) num;
return result;
}
// Suggestion two use pointers to constants
float getAverage( const float *data, const int *num )
{
float result = (*data) / float(*num);
return result;
}
// Suggestion three pass by value since primitives are cheap
float getAverage( float data, int num)
{
float result = data / (float) num;
return result;
}