首頁 >後端開發 >C++ >C程式以字串格式表示分子和分母中的數字

C程式以字串格式表示分子和分母中的數字

WBOY
WBOY轉載
2023-09-01 16:41:071430瀏覽

C程式以字串格式表示分子和分母中的數字

問題

透過使用動態記憶體分配,從使用者在執行時間給出的兩個整數中找到分數部分,並以字串格式表示分子和分母。

解決方案

將分子和分母以字串格式表示的解決方案如下:

範例-

  • 輸入如下:
Numerator1 = 3
Denominator2 = 2

numerator2 = 4
denominator2 = 7
  • 輸出結果如下−
Fractional part1: 1.5
Fractional part2: 0.(571428)

範例

以下是用C寫的程序,用來以字串格式表示分子和分母

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
char* fractionToDecimal(int numerator, int denominator) {
   char *p;
   int psz, n, *dec, dsz, x;
   long long num, den, k, f;
   int i, repeat_at;
   int neg = 0;
   psz = dsz = 100; n = x = 0;
   p = malloc(psz * sizeof(char));
   //assert(p);
   neg = ((numerator > 0 && denominator < 0) ||
   (numerator < 0 && denominator > 0)) ? 1 : 0;
   num = numerator;
   den = denominator;
   num = (num < 0) ? -num : num;
   den = (den < 0) ? -den : den;
   k = num / den;
   f = num % den;
   if (neg && (k || f)) p[n ++] = &#39;-&#39;;
      n += sprintf(&p[n], "%lld", k);
   if (!f) {
      p[n] = 0;
      return p;
   }
   p[n ++] = &#39;.&#39;;
   dec = malloc(dsz * sizeof(int));
   repeat_at = -1;
   if (f < 0) f = -f;
   while (f) {
      for (i = 0; i < x; i += 2) {
         if (dec[i] == f) {
            repeat_at = i;
            goto done;
         }
      }
      if (x + 1 >= dsz) {
         dsz *= 2;
         dec = realloc(dec, dsz * sizeof(int));
      }
      dec[x ++] = f;
      f *= 10;
      k = f / den;
      dec[x ++] = k;
      f = f % den;
   }
   done:
   for (i = 0; i < x; i += 2) {
      if (n + 3 > psz) {
         psz *= 2;
         p = realloc(p, psz * sizeof(char));
      }
      if (repeat_at == i) {
         p[n ++] = &#39;(&#39;;
      }
      p[n ++] = &#39;0&#39; + dec[i + 1];
   }
   if (repeat_at != -1) p[n ++] = &#39;)&#39;;
      p[n ++] = 0;
   free(dec);
   return p;
}
int main(void){
   int n,d;
   printf("enter numerator1 and denominator1:");
   scanf("%d%d",&n,&d);
   printf("n = %d, d = %d ", n, d);
   printf("</p><p>Fractional part1: %s </p><p>",fractionToDecimal(n, d));
   printf("enter numerator2 and denominator2:");
   scanf("%d%d",&n,&d);
   printf("</p><p>n = %d, d = %d ", n, d);
   printf("</p><p>Fractional part2: %s</p><p> ",fractionToDecimal(n, d));
   return 0;
}

輸出

當上述程式被執行時,它產生以下結果−

enter numerator1 and denominator1:4 5
n = 4, d = 5
Fractional part1: 0.8
enter numerator2 and denominator2:5 9

n = 5, d = 9
Fractional part2: 0.(5)

以上是C程式以字串格式表示分子和分母中的數字的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除