c# - How would I go about reducing a fraction? -
this question has answer here:
- how simplify fractions in c#? 5 answers
so have little question. trying reduce fraction in c#. did work check if user entered string , have display message, know how reduce fraction user entered , possibly have program check see if user entered 0 denominator , have display message saying "can't divide zero."
any appreciated!
using system; using system.collections.generic; using system.linq; using system.text; using system.threading.tasks; namespace fractionapplication { class fractionapplicaton { static void main(string[] args) { double numerator; double denominator; string inputdata; bool gooddata; console.write("please enter numerator: "); inputdata = console.readline(); gooddata = double.tryparse(inputdata, out numerator); if (gooddata != true) { console.writeline("the numerator entered contains bad data."); } else { console.write("\nplease enter denominator: "); inputdata = console.readline(); gooddata = double.tryparse(inputdata, out denominator); if (gooddata != true) { console.writeline("the denominator entered contains bad data."); } else { console.writeline("the original fraction was: {0}/{1}",numerator,denominator); } } } } }
this should work.
int temp; if(numerator<denominator)temp = numerator; else temp = denominator; for(int i=temp/2; i>1; i--){ if(numerator%i==0 && denominator%1==0){ //this common denominator , can divide both } } we looking common factor both numerator , denominator. no common factor can larger half size of smaller number, see 1 smaller , set half value. use % remainder of numerator/i , denominator/i.
if both 0 have common factor , since started @ temp/2 , counted down, not 0 counting up, largest common factor. can put anywhere after ensure numerator , denominator valid.
you might want make values ints instead of doubles. won't have 2.01/3.56 fraction right? i'm not sure % operator works doubles.
Comments
Post a Comment