Answer to Question #1936 in C++ for Nikolay

Question #1936
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
#include <cstdio>
#include <cstdlib>
using namespace std;
int main()
{
& char str;
& 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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!