gpt4 book ai didi

c++ - 错误 : Expression must have integral or unscoped enum type

转载 作者:可可西里 更新时间:2023-11-01 16:36:54 28 4
gpt4 key购买 nike

#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];) 时,我得到一个错误“expression must have整数或无作用域的枚举类型。”当我输入数字时,它可以很好地工作直到达到范围数字。之后,从偏差开始算标准差,计算全乱了。

如果我使用 int 作为“大小”并将“temp”保持为 float,它会给我不同的错误。

我该如何解决这个问题?

最佳答案

您的变量 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++ 中是从零开始的,所以这将超出末尾,并且永远不会在原始代码中写入第一个元素。

关于c++ - 错误 : Expression must have integral or unscoped enum type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21341254/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com