首页 > 解决方案 > 创建数组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;
   }

}

标签: c++

解决方案


lengthOfArray是一个常量变量,它的值在初始化在运行时不会改变。

但它的价值 -userInput不是一个常数,它取决于运行时用户输入。正如这里所指出的

常量值是明确的数字或​​字符,例如 1 或 0.5 或“c”。

您应该使用 std::vector 而不是数组,如 Paul Evans 的回答中所建议的那样,或者为 分配一个适当的常量值lengthOfArray,这将在编译时知道,例如:

const int lengthOfArray = 10;

推荐阅读