[英]Pointer variable using float inside an array to calculate the average C++
I am trying to calculate the float using pointer variable, but I am getting an error that I cannot convert 'float*' to 'int*' in initialization. 我正在尝试使用指针变量计算浮点数,但是却收到一个错误,我无法在初始化时将“ float *”转换为“ int *”。 Any ideas how I would go on converting a float to an integer?
任何想法如何将浮点数转换为整数? Thanks a lot.
非常感谢。
int main()
{
float arr[SIZE]={1.1,2.2,3.3,4.4,5.5};
int sum, average, avg=0;
int* end=arr+SIZE;
for(int* ptr=arr; ptr<end; ptr++)
{
sum+= *ptr;
avg = average/sum;
}
cout << "The sum is " << sum;
cout << "The average is " << avg;
}
you can solve it by: append 'f' to each value in the array also only calculate the average outside the loop no inside so in your program you are calculating avg after each sum!! 您可以通过以下方式解决此问题:将'f'附加到数组中的每个值上,也只计算循环外的平均值,而不计算内部的平均值,因此在您的程序中,您要在每次求和后计算平均值!
const int SIZE = 5; // or #define SIZE 5 // I recommend using const
float arr[SIZE] = {1.1f, 2.2f, 3.3f, 4.4f, 5.5f};
float sum = 0, avg = 0;
float* end = arr + SIZE;
for(float* fPtr = arr; fPtr < end; fPtr++)
sum += *fPtr;
avg = sum / SIZE;
cout << "The sum is " << sum << endl;
cout << "The average is " << avg << endl;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.