首页 > 解决方案 > 在 C++ 中将 sqrt(var) 声明为编译时间常数

问题描述

我有一个 c++ 程序,我需要在 for 循环中传递一个数字的平方根。


#include<random>
#include<iostream>
#include<algorithm>
#include<string>
#include<math.h>
#include <stdlib.h>
#include <windows.h>
#include <ctype.h>
#include <omp.h>

using namespace std;
int main()
{
vector<int>inputDataBits(49);                                    // vector of randomly generated input data bits
#ifdef printDebug
    std::cout << "the input data bits are" << endl;
    std::cout << "-------------------------" << endl << endl;
    int var =49;
    const int r=(int)sqrt(var);
    float input2d[r][r];
    for (int i = 0; i < r; i++)
    {
        for (int j = 0; j < r; j++)
        {
            input2d[i][j] = inputDataBits[(j %r) + (i *r)];
            std::cout << input2d[i][j] << "\t";
        }
        std::cout << endl << endl;
    }
    std::cout << endl << endl;
#endif
return 0;
}

我得到一个错误'表达式必须有一个常量值'。有没有办法在 C++ 中做到这一点?

标签: c++

解决方案


这就是constexpr关键字的目的(使值在编译时已知)。

  constexpr int var=49;
  constexpr int r=(int)sqrt(var);

不幸的是,在文档sqrt()中没有声明为constexpr函数。gcc似乎只认为它是可移植的,constexpr但它不是便携式的。


推荐阅读