c - 编辑用户输入而不是内部输入的脚本

标签 c pointers math function-pointers

我有一个简单的脚本,它工作得很好。我的问题是,如何才能以简化的分数形式显示结果?另外,此时我正在自己定义值,有没有办法让脚本要求用户输入所使用的不同分数的分子和分母?

发布的脚本在询问和执行操作方面为我创造了奇迹,所以我对此非常感激。它没有减少分数,我还漏掉了什么吗?

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

最佳答案

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(分子),sqrt(分母)),这也可以。

由于您多次需要它,因此最好将其放入一个函数中并在每次结果上调用它。

关于c - 编辑用户输入而不是内部输入的脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33787851/

相关文章:

c - 打开并配置串口

c - 为什么指针需要在其参数中使用地址运算符来修改结构成员的值?

Java:如何生成大于x的随机数,没有最大值?

c - 模块函数不返回答案

c - 为什么 cmake 在 Windows 上使用 cygwin 为 netcdf 提供 undefined reference ?

c - 在不使用 & 或 * 的情况下使两个指针相等?

c++ - 简单的 AVL 树删除有时只起作用

objective-c - 将索引转换为坐标的算术仅返回索引

jquery - 计算旋转后的新位置

c - 为什么这个 printf 语句需要一个符号?