Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <string.h>
- typedef struct tuple
- {
- int x;
- int y;
- } tuple;
- tuple tupCons(int x, int y)
- {
- tuple res;
- res.x = x;
- res.y = y;
- return res;
- }
- inline int min(int a, int b) { return a<=b ? a : b;}
- tuple fracSimp(int num, int denom)
- {
- int m = min(num,denom);
- int i;
- for(i = m; i > 1; i --)
- if(num %i == 0 && denom %i == 0)
- return fracSimp(num/i,denom/i);
- return tupCons(num,denom);
- }
- int main(int argc, char**argv){
- unsigned char gfrac = 0;
- char * istring = argv[0];
- int i;
- for(i = 1; i < argc; i++)
- {
- if(!strcmp(argv[i],"--help") || !strcmp(argv[i],"-h"))
- {
- printf(
- "Usage: %s [Options] [Fraction]\n"
- "--help\t\t\t\t-h\t\tDisplay this help message\n"
- "--expression\t[fraction]\t-e [fraction]\tUse this fraction\n"
- ,argv[0]);
- return 0;
- }
- if(!strcmp(argv[i],"--expression") || !strcmp(argv[i],"-e"))
- {
- gfrac = 1;
- if(i+1 >= argc)
- {
- printf("%s requires the next argument to be a fraction\n",argv[i]);
- return 1;
- }
- if(argv[i+1][0] =='-')
- {
- printf("%s requires the next argument to be a fraction\n",argv[i]);
- return 1;
- }
- istring=argv[i+1];
- }
- if(argv[i][0]!='-' && !gfrac)
- {
- istring = argv[i];
- gfrac=1;
- }
- }
- int a,b;
- if(!gfrac){
- printf("Give me a fraction (1/2, 9/7, etc): ");
- scanf("%d/%d",&a,&b);
- }else
- {
- sscanf(istring,"%d/%d",&a,&b);
- }
- if(!b)
- {
- printf("ERROR: DIVISION BY 0\n");
- return 1;
- }
- tuple res = fracSimp(a,b);
- if(!gfrac)
- printf("Simplified: %d/%d\n",res.x,res.y);
- else
- printf("%d/%d\n",res.x,res.y);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement