CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 2 of 3 FirstFirst 123 LastLast
Results 16 to 30 of 40

Thread: adding rational number using only class functions

  1. #16
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,149

    Re: adding rational number using only class functions

    Consider this test program
    Code:
    #include <iostream>
    using namespace std;
    
    int main()
    {
    	int x = -3;
    	int y = 3;
    	unsigned int z = x;
    
    	cout << "x: " << x << " y: " << y << " z: " << z << endl;
    	return 0;
    }
    On my system this produces the output
    Code:
    x: -3 y: 3 z: 4294967293
    z is a very large negative number rather than 3.

    To assign a number which may be positive or negative to an unsigned int use the abs() function as described in post #11.
    Last edited by 2kaud; February 23rd, 2015 at 10:52 AM.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++17 Compiler: Microsoft VS2019 (16.6.3)

  2. #17
    Join Date
    Feb 2015
    Posts
    20

    Re: adding rational number using only class functions

    Yeah it is stupid they started me in the 2nd course of 3 course series. so im trying to learn from the basica on my own and try to figure out what they are talking about in class as i go... Thank you for your help thought I do appreciate it

  3. #18
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,149

    Re: adding rational number using only class functions

    Ah! Ok, here's your starter for 10!

    Code:
    #include <iostream>
    using namespace std;
    
    class Rational
    {
    private:
    		unsigned int numerator, denominator;
    		char sign;
    
    public:
    		Rational(int num, int denom = 1);
    		void PrintFraction() const;
    };
    
    Rational::Rational(int num, int denom)
    {
    	//Cannot have divison by 0!
    	if (denom == 0)
    		denom = 1;
    
    	numerator = abs(num);
    	denominator = abs(denom);
    	sign = ((num < 0 && denom >= 0) || (num >= 0 && denom < 0)) ? '-' : '+';
    }
    
    void Rational::PrintFraction() const
    {
    	if (sign == '-')
    		cout << sign;
    
    	cout << numerator;
    
    	if (denominator != 1)
    		cout << "/" << denominator;
    }
    
    int main()
    {
    int numer;
    int denom;
    
    		cout << "enter numerator: ";
    		cin >> numer;
    		cout << "enter denominator: ";
    		cin >> denom;
    
    Rational r1(numer, denom);
    
    	r1.PrintFraction();
    	return 0;
    }
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++17 Compiler: Microsoft VS2019 (16.6.3)

  4. #19
    Join Date
    Jul 2005
    Location
    Netherlands
    Posts
    2,042

    Re: adding rational number using only class functions

    Quote Originally Posted by stratovarios View Post
    i thought about using a bool for the sign because it makes so much sense, but im required to use char in this particular case. could you please explain a little more about what you meant here?
    You start by writing all the tests (in this case unit tests) and then implement your class function by function to pass all the tests. This forces you to first think about all the functionality your class should provide and how to make that functionality as easy to use as possible. Contrary, if you start by implementing your class, the design of your class will more likely end up as something that is easier to implement, but harder to use. That is exactly the opposite of what you want to achieve.

    As a beginner, it may be hard to write good unit tests, because you don't know all the possibilities of the language. But, as you can see, there are plenty of gurus around here who are eager to help.
    Cheers, D Drmmr

    Please put [code][/code] tags around your code to preserve indentation and make it more readable.

    As long as man ascribes to himself what is merely a posibility, he will not work for the attainment of it. - P. D. Ouspensky

  5. #20
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,149

    Re: adding rational number using only class functions

    Quote Originally Posted by stratovarios View Post
    Yeah it is stupid they started me in the 2nd course of 3 course series. so im trying to learn from the basica on my own and try to figure out what they are talking about in class as i go... Thank you for your help thought I do appreciate it
    You may find these sites of interest
    http://www.learncpp.com/
    http://www.cplusplus.com/doc/tutorial/

    Also what book(s) are you using from which to learn c++ - has the class instructor suggested any?
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++17 Compiler: Microsoft VS2019 (16.6.3)

  6. #21
    Join Date
    Apr 2000
    Location
    Belgium (Europe)
    Posts
    4,626

    Re: adding rational number using only class functions

    Quote Originally Posted by 2kaud View Post
    Oh?? Doesn't it ensure that the values of the parameters are not 'accidentally ' changed in the function?
    it does, but...

    You're loading your public interface with "pointless information" and possibly confusing the class consumer.
    For the caller it doesn't matter at all whether the implementation will or will not change the value since it's passed by value and thus only a copy ever gets changed. it's a POD and this can not have any kind of side effects.

    Note that this isn't necessarily true for non-POD classes where there may be 'visible' sideeffects to the caller if the function changes the value parameter.

    But in any case, whenever I see const value parameters, my "spidey sense" starts tingling :-)
    I've seen it be a cause for bugs more often than it has been a means to stop them.

  7. #22
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,149

    Re: adding rational number using only class functions

    For the caller it doesn't matter at all whether the implementation will or will not change the value since it's passed by value and thus only a copy ever gets changed. it's a POD and this can not have any kind of side effects.
    Yes, but I meant that the values of the pass-by-value parameters are not 'accidentally' changed in the function causing a run-time logic error.

    eg
    Code:
    void array(int arr[], const int size)
    {
         //important that size is not changed within this function as this is the number of elements within arr
    }
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++17 Compiler: Microsoft VS2019 (16.6.3)

  8. #23
    Join Date
    Feb 2015
    Posts
    20

    Re: adding rational number using only class functions

    Thank to everyone who posted i really appreciate all the help you guys provided.
    I think i got the program to run properly. i just wanted to give share the final results to see if my addUp function could have been written with less code. It just feels like i'm missing and obvious shortcut. regardless thank you again.

    Code:
    #include <iostream>
    using namespace std;
    
    class Rational
    {
    private:
    		unsigned int numerator, denominator;
    		char sign;
    
    public:
    		Rational();
    		Rational(int num, int denom);
    		void PrintFraction() const;
    		friend Rational addUp(Rational one, Rational two);
    };
    
    
    
    int main()
    {
    
    	Rational sum;
    	int numone,numtwo;
    	int denomone,denomtwo;
    
    		cout << "enter numerator: ";
    		cin >> numone;
    		cout << "enter denominator: ";
    		cin >> denomone;
    
    		cout << "enter numerator: ";
    		cin >> numtwo;
    		cout << "enter denominator: ";
    		cin >> denomtwo;
    
    
    	Rational r1(numone, denomone);
    	Rational r2(numtwo, denomtwo);
    
    	sum = addUp(r1, r2);
    	
    	sum.PrintFraction();
    
    
    
    
    	system ("PAUSE");
    	return 0;
    }
    Rational::Rational()
    {
    	int denom = 1;
    	char sign = '+';
    }
    
    Rational::Rational(int num, int denom)
    {
    	//Cannot have divison by 0!
    	if (denom == 0)
    		denom = 1;
    
    	numerator = abs(num);
    	denominator = abs(denom);
    	sign = ((num < 0 && denom >= 0) || (num >= 0 && denom < 0)) ? '-' : '+';
    }
    
    void Rational::PrintFraction() const
    {
    	if (sign == '-')
    		cout << sign;
    
    	cout << numerator;
    
    	if (denominator != 1)
    		cout << "/" << denominator;
    }
    
    Rational addUp(Rational one, Rational two)
    {
    	
    	Rational total;
    	
    	if (one.sign == '+' && two.sign == '+')
    	{
    		total.sign = '+';
    		total.numerator = one.numerator*two.denominator+two.numerator*one.denominator;
    		total.denominator = one.denominator*two.denominator;
    	}
    
    	else if (one.sign == '-' && two.sign == '-')
    	{
    		total.sign = '-';
    		total.numerator = one.numerator*two.denominator+two.numerator*one.denominator;
    		total.denominator = one.denominator*two.denominator;
    	}
    
    	else
    	{
    		
    		if (one.numerator*two.denominator>two.numerator*one.denominator)
    		{
    			total.sign = one.sign;
    			total.numerator = one.numerator*two.denominator-two.numerator*one.denominator;
    			total.denominator = one.denominator*two.denominator;
    		}
    		else
    		{
    			total.sign = two.sign;
    			total.numerator = two.numerator*one.denominator-one.numerator*two.denominator;
    			total.denominator = one.denominator*two.denominator;
    		}
    	}
    
    	return total;
    }

  9. #24
    Join Date
    Feb 2015
    Posts
    20

    Re: adding rational number using only class functions

    Thank you, these two websites seems really helpful i'll make sure to read through the basics. in regards to a text I dont have a text i just look up definitions online and read examples of other written programs which makes the two websites you mentioned my new go to.

  10. #25
    VictorN's Avatar
    VictorN is online now Super Moderator Power Poster
    Join Date
    Jan 2003
    Location
    Hanover Germany
    Posts
    19,734

    Re: adding rational number using only class functions

    Why did you declare your Rational addUp(...) as friend rather than static?
    Besides, better would be pass the Rational arguments by const reference than by value:
    Code:
    	static Rational addUp(const Rational& one, const Rational& two);
    Victor Nijegorodov

  11. #26
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,149

    Re: adding rational number using only class functions

    Code:
    Rational::Rational()
    {
    	int denom = 1;
    	char sign = '+';
    }
    No! denom and sign are local variables to the constructor. Try
    Code:
    Rational::Rational() : denominator(1), numerator(1), sign('+') {}
    or remove the separate default constructor and have default arguments for the other constructor
    Code:
    Rational(int num = 1, int denom = 1);
    It just feels like i'm missing and obvious shortcut.
    Yes, as you are not simplifying the calculated fraction addUp() can be done in 1 line - although it doesn't help that you are storing the sign separate. It would be even simpler if the sign was stored with the numerator making numerator a signed int with denominator remaining as unsigned int.

    PS Have you actually compiled successfully and run this program?
    Code:
    sum = addUp(r1, r2);
    ???
    Last edited by 2kaud; February 25th, 2015 at 05:30 AM.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++17 Compiler: Microsoft VS2019 (16.6.3)

  12. #27
    Join Date
    Apr 2000
    Location
    Belgium (Europe)
    Posts
    4,626

    Re: adding rational number using only class functions

    Quote Originally Posted by 2kaud View Post
    Yes, but I meant that the values of the pass-by-value parameters are not 'accidentally' changed in the function causing a run-time logic error.

    eg
    Code:
    void array(int arr[], const int size)
    {
         //important that size is not changed within this function as this is the number of elements within arr
    }
    yes, it DOES do that. but...

    Why does a consumer of your class interface need to be made aware that the implementation won't "accidentally" change parameter values when this doesn't matter to the consumer at all, you can't change the caller's copy of the value.

    Yes, it's a logic error (aka bug) if it would have happened and it shouldn't have.
    But are you really going to rely on that by noting that fact as const in the public interface ?

    And what if the implementer decided they needed a changable size, added a
    Code:
    int mysize (size);
    at the start of the function, changed mysize, and then have errors happening as well because of that.
    You can't prevent a programmer from shooting himself in the foot if he really was set out for doing that anyway.
    consting the value parameter won't realistically prevent bugs.

    are you advocating that ALL value parameters should be const just to prevent accidental change in the implementation ? or if not, what is going to be your general rule as to decide when a value parameter should be const or not. And again... why does the consumer of the class need to know that the implementer wanted to "make sure" he wasn't going to shoot himself in the foot by accidentally changing a value parameter.



    in this particular example. trying to const the size because of a flawed approach to data structures (should have used a const vector& or something similar) to then blame the size is just bad approach to things.
    also
    I can change arr, but not change size and cause the same kind of problems ? Forgot to make arr const too ? or why not ?

    Do you really wanna open the can of const worms ? (warning const worms are radioactive, highly toxic and will eat through all materials other than the can they are contained in).

  13. #28
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,149

    Re: adding rational number using only class functions

    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++17 Compiler: Microsoft VS2019 (16.6.3)

  14. #29
    Join Date
    Jul 2005
    Location
    Netherlands
    Posts
    2,042

    Re: adding rational number using only class functions

    Quote Originally Posted by 2kaud View Post
    Yes, as you are not simplifying the calculated fraction addUp() can be done in 1 line - although it doesn't help that you are storing the sign separate. It would be even simpler if the sign was stored with the numerator making numerator a signed int with denominator remaining as unsigned int.
    I would strongly advice against mixing signed and unsigned integers. Just take this simple example:
    Code:
    int numerator = -1;
    unsigned int denominator = 2;
    bool isNegative = (numerator * denominator < 0);
    What do you think the value of isNegative is?
    Due to type promotion the result of the multiplication is an unsigned int, which cannot be negative, so isNegative is false.

    Arithmetics with unsigned values is too prone to errors like this. You are better off just using an int, even if it should never take negative values. Only use unsigned integers when you want to use individual bits as flags.
    Cheers, D Drmmr

    Please put [code][/code] tags around your code to preserve indentation and make it more readable.

    As long as man ascribes to himself what is merely a posibility, he will not work for the attainment of it. - P. D. Ouspensky

  15. #30
    Join Date
    Jul 2005
    Location
    Netherlands
    Posts
    2,042

    Re: adding rational number using only class functions

    Quote Originally Posted by VictorN View Post
    Why did you declare your Rational addUp(...) as friend rather than static?
    What would you gain from making the function static? It only requires more typing.
    Cheers, D Drmmr

    Please put [code][/code] tags around your code to preserve indentation and make it more readable.

    As long as man ascribes to himself what is merely a posibility, he will not work for the attainment of it. - P. D. Ouspensky

Page 2 of 3 FirstFirst 123 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width




On-Demand Webinars (sponsored)