c++ - 创建数组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;
推荐阅读
- ocaml - 在列表 ocaml 中插入元素
- excel - B行中每个单元格的三个条件格式规则-需要帮助复制整个表格
- c# - DbContext 实例同时在两个地方使用 - EF - Hangfire
- javascript - 如何在jquery中动态生成表达式?
- php - 我无法使用 curl 访问所需的网址
- c# - 我可以在 MVC 后端创建一个无状态的静态类吗
- quarkus - com.oracle.truffle.polyglot.PolyglotImpl(在未命名的模块中)无法访问类 org.graalvm.polyglot.impl.AbstractPolyglotImpl
- python - 将大炮正确地朝向玩家 Pygame 旋转仍然存在问题
- java - 如何在android中短时间内显示图像
- c++ - BASS_StreamCreateFile 函数在 C++ 中返回 0