#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");
}
Run Code Online (Sandbox Code Playgroud)
我想从用户那里获得数组的大小,但是当我使用(float *temp = new float[size];)时,我得到一个错误"表达式必须具有整数或未整合的枚举类型." 当我输入数字时,它可以很好地工作直到范围编号.之后,从偏差开始到标准偏差,计算全部搞砸了.
如果我使用int'size'并保持'temp' float,它会给我不同的错误.
我怎样才能解决这个问题?
Ree*_*sey 11
您的变量size声明为:float size;
您不能将浮点变量用作数组的大小 - 它必须是整数值.
您可以将其转换为整数:
float *temp = new float[(int)size];
Run Code Online (Sandbox Code Playgroud)
你的另一个问题可能是因为你在数组范围之外写作:
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];
}
Run Code Online (Sandbox Code Playgroud)
数组在C++中是零基础的,所以这将超越结束,永远不会在原始代码中编写第一个元素.
| 归档时间: |
|
| 查看次数: |
94683 次 |
| 最近记录: |