简单 c 程序中的奇怪输出值

Strange output values in simple c program

我试图在我的 C 程序中计算斐波那契数列,但是当我尝试输出结果时,我得到 4 个奇怪的数字序列,我不知道它们是什么 mean.Are 它们是内存地址还是什么?我做错了什么?

#include <stdio.h>

void fibonacci(int N) {
  if(N == 0) {
    printf("0\n");
  } else if(N == 1) {
    printf("0\n1\n");
  } else { // calculate the fibonacci number
    int temp;
    int i;
      for (i = 0; i <= N; i++) {
          temp += i;
          printf("%d \n",temp);
      }
  }
  return;
}

int main() {
  int n;
  do {
    printf("Please insert a Natural Number: \n");
    scanf("%d",&n);
  } while (n < 0);
  fibonacci(n);
  return 0;
}

您的 Fibonacci 函数中有一个未初始化的变量

int temp;

未初始化变量的访问是undefined behaviour

It is possible to create a variable without a value. This is very dangerous, but it can give an efficiency boost in certain situations. To create a variable without an initial value, simply don’t include an initial value:

// This creates an uninitialized int
int i;

The value in an uninitialized variable can be anything – it is unpredictable, and may be different every time the program is run. Reading the value of an uninitialized variable is undefined behaviour – which is always a bad idea. It has to be initialized with a value before you can use it.

您未能初始化 temp 变量:您需要

int temp = 0;

原因是automatic variables in C have undefined values when they are declared。自动变量(在函数内声明的变量通常是这种类型)在内存中分配存储空间 space,但该存储空间 space 很可能之前已用于其他用途,在这种情况下,无论最后存储什么值你的变量中会有 'appear' 。没有办法知道这个值是多少。养成在声明变量时初始化变量的习惯。