#include <iostream>
#include <vector>
#include <numeric>
using namespace std;
float mean (float num[], float n)
{
int i;
float sum=0;
for(i=0;i<n;i++)
sum=sum+num[i];
return (sum/n);
}
int main()
{
int minusElements;
int n;
cout << "Enter number of Elements:";
cin >> n;
minusElements = n - 1 ;
int i,j, num[n];
float temp;
float f;
for(i=0;i<n;i++)
{
cin >> f;
num.push_back(f);
}
cout << "Enter " << n << " numbers:\n";
for(i=0;i<n;i++)
cin >> num[i];
cin.get();
float m = mean(&num[0], num.size());
}
//33 request for member `push_back' in `num', which is of non-class type `int[((unsigned int)((int)n))]'
//41 request for member `size' in `num', which is of non-class type `int[((unsigned int)((int)n))]' 发布于 2011-08-11 13:04:02
首先要做的是:
int num[numElements]; 这在标准C++中是不允许的。它的可变长度数组(VLA),因为numElements不是const表达式。VLA仅允许在C99中使用。
cout << "Mean:"<< mean(num,n);mean()接受float*,但num的类型是int[],它可以转换为int*,但不能转换为float*。因此出现了错误。
解决方案是:在C++中,使用std::vector<float>作为:
#include <vector> //must include this!
std::vector<float> num;
float f;
for(i=0;i<numElements;i++)
{
cin >> f;
num.push_back(f);
}
//then call mean() as
float m = mean(&num[0], num.size());除此之外,您的mean()函数被错误地实现了。什么是numElements?它是一个未初始化的变量,您在for循环中使用它。这会调用未定义的行为。解决方案是:一开始就不需要numElements。只需使用n作为参数传递给函数即可。
此外,在C++中,您甚至不需要函数来计算平均值,您可以像这样使用<numeric>中的函数:
#include <numeric>
//if num is std::vector
float mean = std::accumulate(num.begin(), num.end(), 0) / num.size();
//if num is float[n] or float* (num of elements = n)
float mean = std::accumulate(num, num + n, 0) / n;好的。因为你是一个初学者,想要学习如何解决这个问题。在你尝试过没有成功之后,下面是你应该怎么做的:
C++中的C风格编码:
#include <iostream>
float mean (float *num, int n)
{
float sum = 0;
for(int i = 0 ; i < n ; i++ )
sum += num[i];
return sum/n;
}
int main()
{
int count;
std::cin >> count;
float *numbers = new float[count]; //allocate memory!
for(int i=0; i< count ;i++)
{
std::cin >> numbers[i];
}
std::cout << mean(numbers, count) << std::endl;
delete [] numbers; //must deallocate the memory!
}Input (后接下一行元素的元素数):
6
12 89 23 12 32 11输出:
29.8333在线演示:http://www.ideone.com/hdZPd
注不推荐使用C++中的C风格编码,但它仅用于学习目的。
C++中的C++样式编码:
#include <iostream>
#include <vector>
#include <numeric>
int main()
{
int count;
std::cin >> count;
std::vector<float> numbers(count);
for(int i=0; i< count ;i++)
{
std::cin >> numbers[i];
}
float mean = std::accumulate(numbers.begin(), numbers.end(), 0.0)/ numbers.size();
std::cout << mean << std::endl;
}Input (后接下一行元素的元素数):
6
12 89 23 12 32 11输出:
29.8333在线演示:http://www.ideone.com/aZ7u8
希望它能帮助你理解这两种风格的问题和解决方案。
发布于 2011-08-11 13:07:54
根据这个问题的标题,我非常确定您的问题出在下面这一行:
int num[numElements], i,j,temp;你的意思是:
int i,j;
// shouldn't be using num[numElements] in c++ (see Nawaz's answer for why)
float num[], temp; // temp *also* should be a fload based on usage.你似乎也有一个额外的for(i=0;i<numElements;i++)
发布于 2011-08-11 13:04:50
是否将int numnumElements更改为float numnumElements?你要发送一个整型数组给需要一个浮点数组的东西。
https://stackoverflow.com/questions/7021028
复制相似问题