开发者

Passing a double to later in a program - using a dialog box for entry

开发者 https://www.devze.com 2023-03-10 13:33 出处:网络
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

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 uninitial开发者_Go百科ised. 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?


When you say:

 sprintf( MaxBuf, "%d", Max);

you are trying to print a double using an integer converter, which will give strange results, depending on what is in Max - you want:

sprintf( MaxBuf, "%f", Max);


I think you want sscanf instead of sprintf - and as @dragon135 mentioned %lf instead of %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 add extern 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 for double, not %d:

sprintf( MaxBuf, "%lf", Max); // Max is of type double


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 as extern int Max; in the header.

Or even better, don't use global variables. ;)

0

精彩评论

暂无评论...
验证码 换一张
取 消