簡體   English   中英

“表達式必須具有恆定值”的錯誤

[英]error with “expression must have a constant value”

我是 C++ 的新手。 我正在嘗試制作一個可以找到平均值、最大值、最小值和中值的程序。 我不確定我在代碼中做錯了什么,我收到double scores[n];

#include <iostream>
#include<iomanip>
#include "ArrayFunction.h"

using namespace std;

int main() 
{
    int n;

    double scores[n];

    cout << "Enter the number of your scores: ";
    cin >> n;
    // creat the input array
     
    // read the elements into the array 
    for (int i = 0; i < n; i++)
    {
        cout << "Enter " << n << " scores: ";
        cin >> scores[i];
    }
    
    // call the functions and display for the result

    cout << "Average of Score is: " << calcAverage(scores, n) << endl;
    cout << "Min     : " << calcMin(scores, n) << endl;
    cout << "Max     : " << calcMax(scores, n) << endl;
    cout << "Median  : " << calcMedian(scores, n) << endl;
}

ArrayFunction.h

template <typename T>
long double calcAverage(T* arr, int size) {
    long double total = 0;
    //Compute the sum
    for (int i = 0; i < size; i++)
        total = total + *(arr + i);
    //return the average 
    return total / size;
}

template <typename T>
T calcMax(T* arr, int size) {
    //Initilize the max
    T max = arr[0];
    //Find the max out of the remaining elements
    for (int i = 1; i < size; i++)
        if (max < arr[i])
            max = arr[i];
    //Return the max element
    return max;
}

template <typename T>
T calcMin(T* arr, int size) {
    //Initilize the min element     
    T min = arr[0];
    //Find the min out of the remaining elements
    for (int i = 1; i < size; i++)
        if (min > arr[i])
            min = arr[i];
    //Return the max element
    return min;
}

template <typename T>
long double calcMedian(T* arr, int size) {
    T temp;
    //Create a temp array
    T arr2[size];
    //Copy the array
    for (int i = 0;i < size;i++)
        arr2[i] = arr[i];
    //Sort the array
    for (int i = 0;i < size - 1;i++) {
        for (int j = i + 1;j < size;j++) {
            if (arr2[i] > arr2[j]) {
                temp = arr2[i];
                arr2[i] = arr[j];
                arr2[j] = temp;
            }
        }
    }
    //IF the size of array is even then we add the mid and min+1 elements
    //compute the average
    if (size % 2 == 0) {
        return (arr2[size / 2] + arr2[size / 2 + 1]) / 2.0;
    }
    //If the size is odd the we return the middle element
    return arr2[size / 2];
}

我嘗試輸入一個數字並得到一個不同的錯誤:

數組類型 T 大小不可分配

我已經搜索並且 C++ 不支持可變長度 arrays,我應該使用std::vector代替。

您可以在編譯時聲明一個已知大小的數組! 所以大小必須是恆定的!

int values[10];
int values2[] ={1,2,3};

constexpr int size = 10;
int values3[size];

const int size2 =5;
int values4[size2];

以上所有示例都是在編譯時使用 const size 定義的!

對於運行時初始化,您可以使用指針!

int* values = new int[1]; 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM