Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <math.h>
- #include <conio.h>
- void input(int *num, int *den); // input numerator (num) and denominator of a fraction (den)
- void display(int num, int den); // display the fraction
- void simplify(int *num, int *den); // simplify the fraction
- int main() {
- int n, d;
- char choice;
- do {
- printf("1. Input fraction\n\n");
- input(&n, &d);
- printf("\n2. Simplify fraction\n\n");
- display(n, d);
- printf("=\n");
- simplify(&n, &d);
- display(n, d);
- do {
- fflush(stdin);
- printf("Another run <y/n>? ");
- scanf("%c", &choice);
- if (choice != 'n' && choice != 'y') {
- printf("Invalid!\n");
- }
- } while (choice != 'n' && choice != 'y');
- if (choice == 'n') {
- break; // ra khoi do-while(1)
- }
- } while (1);
- return(0);
- }
- void input(int *num, int *den) {
- char ch;
- /* input & check validation*/
- while (1) // input numrator
- {
- printf("Enter numerator: ");
- fflush(stdin);
- scanf("%d%c", num, &ch);
- if (ch == '\n') {
- break;
- }
- else {
- printf("Invalid numerator, please re-enter!\n");
- }
- }
- ch = '\0';
- while (1) { // input denominator
- printf("Enter denominator: ");
- fflush(stdin);
- scanf("%d%c", den, &ch);
- if (*den != 0 && ch == '\n') {
- break;
- }
- else {
- printf("Invalid denominator, please re-enter!\n");
- }
- }
- }
- void display(int num, int den) {
- printf("%d/%d\n", num, den);
- }
- int GCD(int a, int b){ /* giai thuat Euclid */
- while (a!=0) {
- if (a == b) {
- break;
- }
- else {
- if (a>b) {
- a = a-b;
- }
- else {
- b = b-a;
- }
- }
- }
- return a;
- }
- void simplify(int *num, int *den) {
- int a = GCD( abs(*num), abs(*den));
- *num /= a;
- *den /= a;
- }
Add Comment
Please, Sign In to add comment