簡體   English   中英

C中的長精確數字?

[英]Long precise numbers in C?

我正在制作一個打印前100個Lucas數字的程序(它們就像Fibonacci),但最后幾個數字不適合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;
}

看起來你需要的只是補充。 我認為有三種方法可以解決這個問題。

  • 如果您不被禁止使用庫,那么您將使用常用的許多bigint庫之一。
  • 實現基於字符串的加法器。 你基本上實現了你在三年級學到的加法。
  • 作為一個黑客,如果你的最大數字大約適合兩個unsigned long long ints那么你可以將你的數字分成最高有效數字和最低有效數字。 我會走這條路。

我用下面的數據存儲了很大的數字。 粘貼下面的代碼並附上一些注釋。 希望能幫助到你。

#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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM