我有一个简单的脚本,它工作正常。我的问题是,如何才能以简化的简化分数显示结果?此外,此时我自己定义了这些值,有没有办法让脚本要求用户输入所用不同分数的分子和分母?
发布的脚本在询问和执行操作方面为我带来了奇迹,所以我非常感谢。它没有减少分数,我还缺少什么吗?
#include<stdio.h>
#include<math.h>
#include<string.h>
int gcd(int a, int b) {
while(0!=b) { int r = a % b; a=b; b=r; }
return a;
}
int input(char* prompt) {
int res;
printf("%s: ", prompt);
scanf("%d", &res);
return res;
}
main()
{
int add,sub,mul,dd;
int add1,sub1,mul1,dd1;
int a,b,c,d;
int fac = gcd(add, add1);
a=input("Please enter the numerator for your first equation:");
b=input("Please enter the denominator for your first equation:");
c=input("Please enter the numerator for your second equation:");
d=input("Please enter the denominator for your second equation:");
add=(a*d+b*c);
add1=(b*d);
add /=fac;
add1/=fac;
printf("\The sum of your fractions is: %d/%d",add,add1);
sub=(a*d-b*c);
sub1=(b*d);
printf("\nThe difference of your fractions is: %d/%d",sub,sub1);
mul=(a*c);
mul1=(b*d);
printf("\nThe product of your fractions is: %d/%d",mul,mul1);
dd=(a*d);
dd1=(b*c);
printf("\nThe quotient of your fractions is: %d/%d",dd,dd1);
}
答案 0 :(得分:0)
for each possible factor from 2 to min (numerator, denominator)
while this factor evenly divides both numerator and denominator
numerator /= factor;
denominator /= factor;
这样做。实际上,你可以上升到min (sqrt (numerator), sqrt (denominator))
,这也可以。
由于您需要多次,最好将其放入一个函数中并在每个结果上调用它。
答案 1 :(得分:0)
查找欧几里德算法。计算两个数字的gcd要比尝试所有可能的素因子更快。
int gcd(int a, int b) {
return (0==b) ? a : gcd(b, a % b);
}
或
int gcd(int a, int b) {
while(0!=b) { int r = a % b; a=b; b=r; }
return a;
}
然后申请,例如总和,作为
fac = gcd(add, add1);
add /=fac;
add1/=fac;
获得减少的数字。
对于您的其他问题,请使用atoi
函数将参数字符串转换为数字或使用scanf
函数提示输入。请注意,C函数不会进行输入验证。
#include ...
int gcd(int a, int b) { ... }
int input(char* prompt) {
int res;
printf("%s: ", prompt);
scanf("%d", &res);
return res;
}
int main() {
...
int a,b,c,d;
a = input("Number for a");
b = input("Number for b");
...