错误:表达式必须具有整数或未整合的枚举类型

时间:2014-01-24 19:49:20

标签: c++

#include <iostream>
#include <iomanip>
#include <string>
#include <algorithm>
#include <sstream>

using namespace std;

int main(){

  float size;

  float sumNum = 0;
  float maxNum, minNum;
  float mean;
  float totalDev = 0;
  float devSqr = 0;
  float stdDev;

  //Create a user input size
  std::cout << "How many number would you like to enter? ";
  std::cin >> size;
  float *temp = new float[size];

  //Getting input from the user
  for (int x = 1; x <= size; x++){
    cout << "Enter temperature " << x << ": ";
    cin >> temp[x];
  }

  //Output of the numbers inserted by the user
  cout << endl << "Number --- Temperature" << endl << endl;
  for (int x = 1; x <= size; x++){
    cout << "   " << x << "   ---     " << temp[x] << endl;
    sumNum = sumNum + temp[x];
  }

  //Calculating the Average
  mean = sumNum / size;
  maxNum = minNum = temp[1];

  for (int x = 1; x <= size; x++){
    if (maxNum < temp[x]){
      maxNum = temp[x];
    }
    if (minNum > temp[x]){
      minNum = temp[x];
    }
  }

  //Calculating Sample Standard Deviation
  for (int x = 1; x <= size; x++){
    totalDev = totalDev + (temp[x] - mean);
    devSqr = devSqr + (pow((temp[x] - mean), 2));
  }
  stdDev = sqrt((devSqr / (size - 1)));

  cout << endl << "The sum: " << sumNum << endl; //the sum of all input
  cout << "The mean: " << mean << endl; //calculate the average 
  cout << "Maximum number: " << maxNum << endl; // print biggest value
  cout << "Minimum number: " << minNum << endl; // print smallest value
  cout << "The range between the maximum and the minimum: " << maxNum - minNum << endl; //the range
  cout << "Deviation: " << totalDev << endl;
  cout << "The squares of deviation: " << devSqr << endl;
  cout << "The Standard Deviation: " << setprecision(1) << fixed << stdDev << endl;

  system("pause");
}

我想从用户那里获得数组的大小,但是当我使用(float *temp = new float[size];)时,我得到一个错误“表达式必须具有整数或未整合的枚举类型。”当我输入数字时,它可以很好地工作直到范围编号。之后,从偏差开始到标准偏差,计算全部搞砸了。

如果我使用int作为'size'并将'temp'保持为float,则会给出不同的错误。

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:9)

您的变量size声明为:float size;

您不能将浮点变量用作数组的大小 - 它必须是整数值。

您可以将其转换为整数:

float *temp = new float[(int)size];

你的另一个问题可能是因为你在数组范围之外写作:

   float *temp = new float[size];

    //Getting input from the user
    for (int x = 1; x <= size; x++){
        cout << "Enter temperature " << x << ": ";

        // cin >> temp[x];
        // This should be:
        cin >> temp[x - 1];
    }

数组在C ++中基于零,因此这将写入超出最终结果,并且永远不会在原始代码中编写第一个元素。