#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");
}I want to get the size of the array from the user, but when I'm using (float *temp = new float[size];), I got an error "expression must have integral or unscoped enum type." When I input the number, it working nicely up until to the range number. After that, start from deviation to the standard deviation, the calculation all messed up.
If I use int for the 'size' and keep the 'temp' as float, it gave me different error.
How can I fix this?
11 Answer
Your variable size is declared as: float size;
You can't use a floating point variable as the size of an array - it needs to be an integer value.
You could cast it to convert to an integer:
float *temp = new float[(int)size];Your other problem is likely because you're writing outside of the bounds of the array:
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]; }Arrays are zero based in C++, so this is going to write beyond the end and never write the first element in your original code.
4