How do I read string say -5/-10 and then reduce the first number and second number to lowest terms.?
my code right now to do everything EXCEPT that it will only work if input is in this format: -5 -10
I need to know how to read it as -5/-10 (a string) and then Write a program that gets a fraction and displays both the fraction and the fraction reduced to lowest terms.
Input is: -5/-10
Output should be: 1/2
1
Expert's answer
2011-06-22T09:58:45-0400
#include <cstdio> #include <cstdlib> using namespace std; int main() { & char str[256]; & int nominator,denominator,gcd; & /* Input the string */ & scanf("%s",str); & int i=0; & /* Divide nominator and denominator by null-symbol */ & while (str[i]!='/') ++i; & str[i]='\0'; & /* Convert nominator as string to integer */ & nominator = atoi(str); & /* Now copy denominator as string to integer */ & denominator = atoi(str+i+1); /* Denominator's string starts from position i+1 */ & printf ("Fraction %i/%i",nominator,denominator); & /* Denominator must be positive number */ & if (denominator < 0) & { denominator = -denominator; nominator = -nominator; & } & /* Find GCD of two numbers */ & int a=abs(nominator), b=denominator; & while (a!=0 && b!=0) & { if (b>a) b %= a; else a %= b; if (a==0) gcd = b; else if (b==0) gcd = a; & } & if (gcd>1) & { nominator /= gcd; denominator /= gcd; & } & printf(" can be reduced to %i/%i\n",nominator,denominator); & system("PAUSE"); & return 0; }
Numbers and figures are an essential part of our world, necessary for almost everything we do every day. As important…
APPROVED BY CLIENTS
Finding a professional expert in "partial differential equations" in the advanced level is difficult.
You can find this expert in "Assignmentexpert.com" with confidence.
Exceptional experts! I appreciate your help. God bless you!
Comments
Leave a comment