在程序中将双精度值传递给后面的内容 - 使用对话框进行输入
我试图传递一个稍后在我的程序中使用的双精度值。程序启动时,会出现一个对话框,要求输入数字。以下代码应该接收数字条目,并将其转换为要传递的双精度数:
char MaxBuf[256];
#ifdef WIN32
edit_dialog(NULL,"Max", "Enter Max:", MaxBuf,260);
#endif
sprintf( MaxBuf, "%d", Max);
请注意,“Max”在头文件中被定义为全局变量,方式如下:
double Max;
但是,当我达到在我的程序的后一点(单独的 C++ 文件中的单独子例程)中,Max 的值未初始化。我知道该变量在头文件中定义正确,因为这以前对我有用;我刚刚意外删除了“main.c”文件中的代码,并正在尝试恢复它。因此问题一定出在最上面的代码块上。我做错了什么?
I am trying to pass a double that is used later in my program. When the program launches, a dialog box appears, asking for a number to be input. The following code is supposed to receive entry of the number, and convert it into a double to be passed on:
char MaxBuf[256];
#ifdef WIN32
edit_dialog(NULL,"Max", "Enter Max:", MaxBuf,260);
#endif
sprintf( MaxBuf, "%d", Max);
Please note that 'Max' is defined as a global variable in a header file, in the following manner:
double Max;
However, when I reach the later point in my program (a separate subroutine in a separate C++ file), the value of Max is uninitialised. I know that the variable is defined correctly in the header file as this has worked previously for me; I have just deleted my code in the 'main.c' file by accident and am trying to restore it. Therefore the problem must lie in the top block of code. What have I done wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当你说:
你正在尝试使用整数转换器打印双精度数,这会给出奇怪的结果,具体取决于 Max 中的内容 - 你想要:
When you say:
you are trying to print a double using an integer converter, which will give strange results, depending on what is in Max - you want:
我认为你想要
sscanf
而不是sprintf
- 正如 @dragon135 提到的%lf
而不是%d
I think you want
sscanf
instead ofsprintf
- and as @dragon135 mentioned%lf
instead of%d
首先,在头文件中定义变量并不是一个好的做法,因为包含该标头的每个文件都会有自己的变量版本(除非您使用一些<保护宏观来预测这一点)。
这就是为什么您会遇到未初始化的变量,因为它与您之前初始化的变量不同。
相反,您最好在 C++ 文件中定义变量
double Max;
,然后在相应的头文件中添加extern double Max;
。这样一来,即使头文件被多个文件包含,变量也只有一个定义。顺便说一句,您应该使用
%lf
表示double
,而不是%d
:First of all, defining variable in a header file is not a good practice because every file that includes that header will have its own version of the variable (unless you use some guarding macro to anticipate this).
That is why you experience uninitialized variable because it is different variable with the variable you have initialized before.
Instead, you better define the variable
double Max;
in the C++ file then addextern double Max;
in the corresponding header file. This way there will only be one definition of the variable even if the header file is included by more than one file.By the way, you should use
%lf
fordouble
, not%d
:听起来每个翻译单元(基本上意味着源文件)都在获取自己版本的全局变量。
您应该仅在一个文件中将其定义为
int Max;
,并在标头中将其定义为extern int Max;
。或者更好的是,不要使用全局变量。 ;)
It sounds like each translation unit (basically that means source file) is getting its own version of the global variable.
You should define it as
int Max;
in only one file, and asextern int Max;
in the header.Or even better, don't use global variables. ;)