簡體   English   中英

創建數組時表達式必須有常量值錯誤 C++

[英]Expression must have a constant value error when creating an array C++

再會。 創建數組時遇到錯誤“表達式必須具有常量值”。 找到這個問題c++ array - expression must have a constant value ,但是這些提示並沒有解決問題。 請幫忙,我很抱歉有這樣的要求,我剛開始學習 C++

代碼:

#include <iostream>
#include <math.h>
#include <cstdlib>
#include <string>
#include <sstream>
#include <conio.h>
#include <random>

int main()
{
   int userInput = 0, sumEvenIndexElements = 0, sumElementsBeetwenZero = 0;
   bool checkZeroElements = false;
   std::cout << "Write array length:" << std::endl;
   std::cin >> userInput;
   const int lengthOfArray = userInput;
   int numbers [lengthOfArray];
   std::default_random_engine generator;
   std::uniform_int_distribution<int> distribution(-10, 10);

   for (int index = 0; index < lengthOfArray; index++)
   {
      numbers[index] = new int[distribution(generator)];
      std::cout << numbers << std::endl;

      if (index % 2 == 0)
      {
         sumEvenIndexElements += *numbers[index];
      }

   }

   std::cout << "Sum even index elements: " << sumEvenIndexElements << std::endl;

   for (int index = 0; index < lengthOfArray; index++)
   {
      numbers[index] = new int[distribution(generator)];

      if (numbers[index] == 0)
      {
         checkZeroElements = !checkZeroElements;
      }

      if (checkZeroElements)
      {
         sumElementsBeetwenZero += *numbers[index];
      }

   }

   if (checkZeroElements)
   {
      std::cout << "Sorry, array have less than two zero elements.";
   }
   else
   {
      std::cout << "Sum even index elements: " << sumEvenIndexElements << std::endl;
   }

}

lengthOfArray是一個常量變量,它的值初始化后的運行時不會改變。

但它的價值 - userInput不是一個常數,它取決於運行時用戶輸入。 正如這里指出的

常量值是一個明確的數字或​​字符,例如 1 或 0.5 或“c”。

您應該使用 std::vector 而不是數組,如 Paul Evans 的回答中所建議的,或者為lengthOfArray分配一個適當的常量值,這將在編譯時已知,例如:

const int lengthOfArray = 10;

您的代碼:

   std::cout << "Write array length:" << std::endl;
   std::cin >> userInput;
   const int lengthOfArray = userInput;
   int numbers [lengthOfArray];

根據您收到的編譯器錯誤將無法正常工作。

std::vector表現要好得多:

   std::cout << "Write array length:" << std::endl;
   std::cin >> userInput;
   const int lengthOfArray = userInput;
   std::vector<int> numbers(lengthOfArray, 0);

將創建一個長度為lengthOfArrayint std::vector全部初始化為0

暫無
暫無

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

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