通过 header 文件使用时 C 中源文件的奇怪输出

Weird output of source file in C when used through header file

我目前正在忙着用 C 编写一个小的掷骰子游戏,但我遇到了一个奇怪的错误。

我在程序的源文件中有代码 运行,我也将其放入 header 文件并将其包含在我的 main() 函数中。

发生的情况是,如果我 运行 掷骰子程序本身作为它自己的程序,我会得到正确的结果。一旦我 运行 它和 link 它通过 header 我得到了数百个奇怪的结果,例如两个骰子的输出是 927,这是没有意义的.

代码如下

Dice.h

int Roll_Dice(void); //haven't used headers a lot so i just have this placed in there.

Dice_roll.c

#include <stdio.h>
#include <time.h>
#include <stdlib.h>


int Roll_Dice(void)
{
setvbuf(stdout, 0, _IONBF, 0);
int dice1 = 0;
int dice2 = 0;
int dice_roll= 0;
int sides;
int i = 0;   
srand(time(NULL));
{
rollagain:   
printf("how many sides of the dice are there? (maximum 8)");
scanf ("%d", &sides);

        if (sides > 9)
    {
        printf("this is not a valid input, must be 8 or less\n ");

        goto rollagain;
       } else {
    dice1 = (rand() % sides) + 1; //pretty self explantory
    dice2 = (rand() % sides) + 1;
    dice_roll = dice1 + dice2;

 }

printf("the number you rolled was %d", dice_roll);
return 0; 
// tried changing this to return "dice_roll" but still got weird outputs when using it with a header.

 }


}

Main.c

#include <stdio.h>
#include <string.h>
#include "Dice.h"


int main(void)
{
printf("%d", Roll_Dice()); simple thing to call the function, don't actually know if this is correct.
}

如果有人能指出为什么它会在主文件中给我一个奇怪的输出,我将不胜感激。

有几点要提一下。

  1. Dice_roll.c 中包含 <stdlib.h> 以获得 srand()rand()

  2. 的原型
  3. 去掉Dice_roll.cint Roll_Dice(void);中的;。您需要在调用和声明函数时使用 ;,而不是在函数定义时。

  4. side 进行额外检查,使其不包含 <=0

  5. 的值
  6. 要将 side 限制为最大值 8,请将 if (sides > 9) 更改为 if (sides > 8)

注意:您可能希望将 srand(time(NULL));Roll_Dice() 函数移动到 main() 中。


编辑:

根据以下评论中的信息,问题是两个连续 printf() 并排打印的输出使输出 出现 错误。