小數轉化為分數


輸入一個小於1的正小數,分別輸出最簡分數的分子和分母。

此代碼的目的是簡單快速的求出有限位小數對應的最簡真分數。

C語言代碼如下:

# include <stdio.h>
# include <string.h>

// 判斷兩個整數的最大公約數是否為1
int is_prime(int a, int b)
{
	while (a != b)
	{
		a>b?(a-=b):(b-=a);
	}
	return b;
}

int main(void)
{
	char ch[50];
	int a=0, b=1;
	int i = 0, flag=0,temp;
	gets(ch);
	// 讀取尾數長度
	while (ch[i])
	{		
		if (flag == 1)
		{
			a += (ch[i]-'0');
			a *= 10;
	 		b *= 10;
		}	
		if (flag==0 && ch[i]=='.')
			flag = 1;
		i++;
	 } 
	a /= 10;

	temp = is_prime(a,b);
	
	while (1 != temp)
	{
		a /= temp;
		b /= temp;
		temp = is_prime(a,b);
	}
	printf("%d %d\n",a,b);
	
	return 0;
 } 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM