简体   繁体   English

C ++错误:初始化器元素不是常量

[英]C++ error: initializer element is not constant

I can't get this simple C++ code to work: 我无法使这个简单的C ++代码正常工作:

int secInt = 5;

double rubbish = secInt/60;

double factor = floor(rubbish);

I always get " ERROR: initializer element is not constant " from line 3 我总是从第3行得到“ 错误:初始化元素不是常量

Factor always returns 0.00 in the log 因子始终在日志中返回0.00

Could anyone help with this, I'm feeling that I overlooked something very simple. 任何人都可以帮忙,我觉得我忽略了一些非常简单的事情。

An example of this error can be seen here: http://ideone.com/2Wrkr9 可以在这里看到此错误的示例: http : //ideone.com/2Wrkr9

Your code should be inside the main portion of your program: 您的代码应位于程序的main部分内:

int main()
{
    int secInt = 583;

    double rubbish = secInt/60.0;

    double factor = floor(rubbish);
}

You should also use standard C++ headers like <cmath> . 您还应该使用标准的C ++标头,例如<cmath>

You forgot to enclose the code in a function. 您忘记了将代码包含在函数中。

Try this. 尝试这个。

int main()
{
    int secInt = 5;

    double rubbish = secInt/60.0;

    double factor = floor(rubbish);
}

C++ will begin executing code in the function named main , and from there, call whatever functions are called from main. C ++将开始在名为main的函数中执行代码,然后从那里调用从main调用的任何函数。

double rubbish = secInt/60;

should be 应该

double rubbish = static_cast<double>(secInt)/60;

since secInt =5 , so floor(rubbish) should be 0 even with the above correction. 由于secInt =5 ,因此即使进行了上述校正, floor(rubbish)应为0

You should have at least a main function if you do not have any other function in your source file. 如果源文件中没有任何其他功能,则至少应具有main功能。 main is the entry point. main是入口点。

int main()
{
 int secInt = 5;
 double rubbish = static_cast<double>(secInt)/60.0;

 double factor = floor(rubbish);
 return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM