【问题标题】:Long precise numbers in C?C中的长精确数字?
【发布时间】:2015-11-19 03:45:36
【问题描述】:

我正在编写一个程序来打印前 100 个卢卡斯数字(它们就像斐波那契),但最后几个数字不适合 unsigned long long int。我尝试使用 long double,但它并不精确,而且我得到的结果与我应该得到的有所不同。

这是一个家庭作业,我的老师特别指定我们不需要使用除 stdio.h 之外的任何其他库。

我尝试制作一种将字符串添加为数字的方法,但这超出了经验,我真诚地怀疑这是我们必须做的。

如果不精确,它看起来像这样:

#include <stdio.h>

int main()
{
    long double firstNumber = 2;
    long double secondNumber = 1;
    long double thirdNumber;

    int i;
    for (i = 2; i <= 100; i += 1)
    {
        thirdNumber = secondNumber + firstNumber;
        firstNumber = secondNumber;
        secondNumber = thirdNumber;
        printf("%Lf, ", thirdNumber);
    }

    return 0;
}

【问题讨论】:

  • 你了解数组吗?例如,您可以将单个“数字”存储为一个数字数组,其中每个元素包含 0 到 9。由于操作只是加法,因此实现数组加法应该很容易(不要忘记在加法后进行标准化)。
  • @WhozCraig 根据 WolframAlpha 的说法,一个 64 位无符号整数的最大值是 18446744073709551615,但 L100 是 792070839848372253127wolframalpha.com/input/?i=what+is+the+100th+Lucas+number%3F
  • 了解bignums 并查看gmplib.org
  • 最好的方法是使用数组和做老派数学。

标签: c types


【解决方案1】:

看起来你只需要添加。我看到了三种方法可以解决这个问题。

  • 如果您没有被禁止使用库,那么您可以使用许多常用的 bigint 库之一。
  • 实现基于字符串的加法器。你基本上会实现你在三年级学到的加法方法。
  • 作为一个小技巧,如果您的最大数字大约适合两个unsigned long long ints,那么您可以将您的数字分成最高有效数字和最低有效数字。我会走这条路。

【讨论】:

  • 我尝试使用库,但到目前为止我只在 .Net 上编程并且没有这方面的经验。看起来很简单...我下载了 bign.lib 或类似的东西并将其包含在内,但由于某种原因编译器没有将 big_n 识别为新类型...
  • 我认为你的老师不希望你使用图书馆(评分会很痛苦)。但是,如果您坚持,请查看有关如何在您的平台上使用库的新手指南。较新的语言已经自动化了很多使用库需要做的事情,C 和 C++ 仍然让你手动完成。听起来您需要包含另一个标头,但如果您对库感到困惑,请针对该问题提出一个单独的问题。
  • 将数字存储为字符串效率非常低
  • @LưuVĩnhPhúc 没关系。 L_100 仍然只有 21 位,因此对于 最低 效率的方法,程序不需要超过 70 字节的存储空间,它只需要计算 100 次加法。
【解决方案2】:

我在下面使用了将非常大的数字存储在一个数组中。用一些 cmets 粘贴下面的代码。希望对您有所帮助。

#include<stdio.h>
int main()
{
    int t;
    int a[200]; //array will have the capacity to store 200 digits.
    int n,i,j,temp,m,x;

    scanf("%d",&t);
    while(t--)
    {
       scanf("%d",&n);
       a[0]=1;  //initializes array with only 1 digit, the digit 1.
       m=1;    // initializes digit counter

       temp = 0; //Initializes carry variable to 0.
       for(i=1;i<=n;i++)
       {
            for(j=0;j<m;j++)
            {
               x = a[j]*i+temp; //x contains the digit by digit product
               a[j]=x%10; //Contains the digit to store in position j
               temp = x/10; //Contains the carry value that will be stored on later indexes
            }
             while(temp>0) //while loop that will store the carry value on array.
             { 
               a[m]=temp%10;
               temp = temp/10;
               m++; // increments digit counter
             }
      }
              for(i=m-1;i>=0;i--) //printing answer
              printf("%d",a[i]);
              printf("\n");
    }
    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-07
    • 2021-11-13
    • 1970-01-01
    • 1970-01-01
    • 2021-07-08
    • 1970-01-01
    相关资源
    最近更新 更多