C中的Fibonacci序列产生负数? [英] Fibonacci Sequence in C generating negatives?

查看:139
本文介绍了C中的Fibonacci序列产生负数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是编程新手,需要C语言帮助。我正在编写一个程序,为最多1000位的值生成Fibonacci序列。

I'm new to programming and need help in C. I am writing a program to generate a Fibonacci sequence for values with up to 1000 digits.

这是我的代码:

#include <stdio.h>

int main(void)
{
    int seq[1000];
    int i,n;

    printf("How many Fibonacci numbers do you want?: ");
    scanf("%d",&n);

    seq[0] = 0;
    seq[1] = 1;

    for(i = 2; i < n; i++)
        seq[i] = seq[i-1] + seq[i-2];

    for (i = 1; i < n; i++)
        printf("%d: %d\n", i, seq[i]);

    return 0;
}

现在的问题是,这些数字都是正确的,直到第47个数字。然后它变得疯狂,并且有负数,而且一切都错了。任何人都可以在我的代码中看到错误吗?非常感谢任何帮助。

Now the problem is, the numbers are all correct up until the 47th number. Then it just goes crazy and there's negative numbers and its all wrong. Can anyone see the error in my code? Any help is greatly appreciated.

推荐答案


我正在编写一个程序来为值生成Fibonacci序列最多1000位数。

I am writing a program to generate a Fibonacci sequence for values with up to 1000 digits.

不是你不是。您将值存储在 int 类型的变量中。通常这样的变量是32位值,并且最大可能值 2 ^ 31 - 1 。这相当于 2,147,483,647 ,这远远超过了达到1,000位数的目标。

Not yet you aren't. You are storing the values in variables of type int. Commonly such variables are 32 bit values and have a maximum possible value of 2^31 - 1. That equals 2,147,483,647 which is some way short of your goal of reaching 1,000 digits.

47 th 斐波纳契数是第一个超过 2,147,483,647 的数字。根据 Wolfram Alpha ,价值为 2,971,215,073

The 47th Fibonacci number is the first number to exceed 2,147,483,647. According to Wolfram Alpha, the value is 2,971,215,073.

当你的程序试图计算这样一个数字时,它会遇到整数溢出,因为真值不能存储在 INT 。您可以尝试准确分析溢出时发生的情况,为什么看到负值,但它确实不会让您走得太远。简单地说,你正在尝试的是 int

When your program attempts to calculate such a number it suffers from integer overflow, because the true value cannot be stored in an int. You could try to analyse exactly what happens when you overflow, why you see negative values, but it really doesn't get you very far. Simply put, what you are attempting is clearly impossible with int.

为了达到1,000位,你需要使用大整数类型。没有任何内置类型可以处理您想要处理的数字。

In order to reach 1,000 digits you need to use a big integer type. None of the built-in types can handle numbers as large as you intend to handle.

这篇关于C中的Fibonacci序列产生负数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆