I have the code
我有代码
#include <stdio.h>
#include <math.h>
double x = round(3.2/2.0);
int main()
{
printf("%f", x);
}
When I try to compile, I get the error initializer element is not a compile-time constant. Without round
, it compiles without a hitch.
当我尝试编译时,我得到的错误初始化元素不是编译时常量。没有圆形,它编译顺利。
I want to round x while having it as a global variable. Is this possible?
我希望将x作为全局变量进行舍入。这可能吗?
2 个解决方案
#1
3
In C language objects with static storage duration can only be initialized with integral constant expressions. You are not allowed to call any functions in integral constant expressions.
在C语言中,具有静态存储持续时间的对象只能使用整数常量表达式进行初始化。不允许在整数常量表达式中调用任何函数。
You will have to find a way to generate your value through an integral constant expression. Something like this might work
您必须找到一种通过整数常量表达式生成值的方法。这样的事可能有用
double x = (int) (3.2 / 2.0 + 0.5);
#2
2
You can't call a function in the global scope, try
您无法在全局范围内调用函数,请尝试
#include <math.h>
double x;
int main(void)
{
x = round(3.2 / 2.0);
return 0;
}
#1
3
In C language objects with static storage duration can only be initialized with integral constant expressions. You are not allowed to call any functions in integral constant expressions.
在C语言中,具有静态存储持续时间的对象只能使用整数常量表达式进行初始化。不允许在整数常量表达式中调用任何函数。
You will have to find a way to generate your value through an integral constant expression. Something like this might work
您必须找到一种通过整数常量表达式生成值的方法。这样的事可能有用
double x = (int) (3.2 / 2.0 + 0.5);
#2
2
You can't call a function in the global scope, try
您无法在全局范围内调用函数,请尝试
#include <math.h>
double x;
int main(void)
{
x = round(3.2 / 2.0);
return 0;
}