Home > Net >  C -> How do I get the result as a fraction?
C -> How do I get the result as a fraction?

Time:08-11

I´m new at programming with C.

The code looks like this now. Its a calculator which operates with " ". The first fraction is 1/1. The second fraction is 1/2. The result of this is 0.50. My question is how do I get the result as a fraction and a decimal number? I have a picture at the bottom. Zähler is numerator and Nenner is called denumerator in german. Thank you very much for your help and sorry for my bad english...

#include <stdio.h>
#include <math.h>
#include <stdlib.h>

int main(void)

{
    // Eingabe der ersten und zweiten rationalen Zahl sowie des Operators


    system("chcp 1252 > nul");
    double z1, n1, z2, n2;
    char op;


    // z1 = Zähler 1 , n1 = Nenner 1, z1/n1 = Bruch 1
    printf("Eingabe der ersten rationalen Zahl\n");
    printf("Zähler 1:");
    scanf("%lf", &z1);
    printf("Nenner 1:");
    scanf("%lf", &n1);


    // op = Operator
    printf("Eingabe des Operators  , -, *, /:\n");
    scanf("%s", &op);

    // z2 = Zähler 2,  n2 = Nenner 2, z2/n2 = Bruch 2
    printf("Eingabe der zweiten rationalen Zahl\n");
    printf("Zähler 2:");
    scanf("%lf", &z2);
    printf("Nenner 2:");
    scanf("%lf", &n2);


    // Addition

    if (op == ' ')
    {
        printf("Summe aus Bruch 1 und Bruch 2:\n");
        printf("%.lf/%.lf   %.lf/%.lf = %.lf/%.lf", z1, n1, z2, n2, (z1/n1)   (z2/n2));
            -**> do I need to change something up here to get a fraction after the decimal number?**
    }

Best regards

Eduard

CodePudding user response:

Use correct specifier

To save an single non-white-space character, use " %c"

char op;
....
// scanf("%s", &op);
scanf(" %c", &op);

Math

how do I get the result as a fraction ...?

Multiply the first fraction by n2/n2 and the 2nd by n1/n1, then add.

double top = z1*n2   z2*n1;
double bottom = n1*n2;

printf("%g/%g\n", top, bottom);

This may not be the simplest form. Additional work needed to reduce.

how do I get the result as .... a decimal number?

printf("%g\n", top / bottom);

CodePudding user response:

Start with an example or two (or three)

0.142857 is approximately 1/7.

What is 14/100? That's equal to 7/50. That's an approximate version of 1/7.

What is 143/1000? That's 71.5/500... Getting closer!

What is 1429/10000? That's 714.45/500... Even closer!

So, just by multiplying the decimal by 10^x and using 10^x as the denominator, then trying to find common divisors, you approximate the decimal with a ratio...

You could investigate GCD (Greatest Common Divisor) as suggested by user3386109.

  • Related