Thread: Finding Ratio of Two Variables Input by User

  1. #1
    Registered User
    Join Date
    Mar 2015
    Posts
    384

    Finding Ratio of Two Variables Input by User

    In Programming: Principles and Practice Using C++ (2nd Edition), there's an exercise question asking to take in a user's input and store them as int variables, and then to find the sum, product, larger, smaller and ratio of the two numbers. I can do the others perfectly fine, but I'm having trouble with the ratio. And I see that I can't use std::ratio for this, either, since it requires constant values rather than variable values.

    There are also some others I don't really get how to do, so I'll ask about them here as well:

    6 Write a program that prompts the user to enter three integer values, and then outputs the values in numerical sequence separated by commas. So, if the user enters the values 10 4 6, the output should be 4, 6, 10. If two values are the same, they should just be ordered together. So, the input 4 5 4 should give 4, 4, 5.
    7 Do exercise 6, but with three string values. So, if the user enters the values Steinbeck, Hemingway, Fitzgerald, the output should be Fitzgerald, Hemingway, Steinbeck.

    8 Write a program to test an integer value to determine if it is odd or even. As always, make sure your output is clear and complete. In other words, don’t just output yes or no. Your output should stand alone, like The value 4 is an even number. Hint: See the remainder (modulo) operator in §3.4.

    9 Write a program that converts spelled-out numbers such as “zero” and “two” into digits, such as 0 and 2. When the user inputs a number, the program should print out the corresponding digit. Do it for the values 0, 1, 2, 3, and 4 and write out not a number I know if the user enters something that doesn’t correspond, such as stupid computer!.
    For the program that would check if a number is even or odd, should I use an if-statement that checks if a number is divisible by 2 to see if it's an even number? If so, then how do I check for odd numbers, since some odd numbers aren't even divisible by 3 anyway (otherwise it'd have made sense to divide by 3). And is it because of the division that the book says to use the modulo operator in this, is there some other reason?

    And as for #10, I wonder if I only have to do it for those particular numbers (0, 1, 2, 3, and 4). And now I also that it'd have been if I'd tried to figure out better how to do this when Jumping Into C++ said to do it in one of the practice problems.

    Any help anybody can provide will be much appreciated. Thanks in advance.

  2. #2
    Guest
    Guest
    Regarding the even-odd problem, have a look at the modulo operator as the book suggests.
    Code:
    for(unsigned i = 0; i < 10; ++i) {
        std::cout << i <<" % 2 = "<< (i % 2) <<"\n";
    }
    The output of above loop should give you a hint.

    For problems #6 and #7, if you're allowed to use std::vector, you should definitely give std::sort (<algorithm> header) a try, it does exactly that.
    Last edited by Guest; 04-04-2015 at 11:36 AM.

  3. #3
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by Osman Zakir View Post
    In Programming: Principles and Practice Using C++ (2nd Edition), there's an exercise question asking to take in a user's input and store them as int variables, and then to find the sum, product, larger, smaller and ratio of the two numbers. I can do the others perfectly fine, but I'm having trouble with the ratio. And I see that I can't use std::ratio for this, either, since it requires constant values rather than variable values.
    You will have to show your code if we are to be able to figure out what's wrong. I can make a guess, though, and that's integer division. If the two operands you're trying to divide are both integers, then the result will also be an integer, so e.g. 2/3 = 0, not 0.6667. Make sure one of your operands are a float or double, or multiply one of them with 1.0 to ensure you get your decimals.

    For 6), it essentially boils down to sorting your input. There are built-in sorting methods in the standard library. Check cppreference.com.

    7) is essentially the same as 6), only with strings instead of integers. Yes, sorting works with strings, as well, so no problem there.

    8) How do we know if a number if odd or even in real life? Well, if it's divisable with 2, we know it's even. And if it's not even, then it's odd. How do we know a number if divisable by a certain number? We check that the remainder of the division. This can be done with the modulus operator.

    And as for #10, I wonder if I only have to do it for those particular numbers (0, 1, 2, 3, and 4). And now I also that it'd have been if I'd tried to figure out better how to do this when Jumping Into C++ said to do it in one of the practice problems.
    Not sure what your question is here. Can you clarify?

    Last but not least, if you have problems with exercises, post your code along with what exactly you're having trouble with. If the code does not compile, also post the compile errors.

    Oh, and I should mention that Jumping into C++ is bad book. I suggest you start with Accelerated C++ first.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  4. #4
    Registered User
    Join Date
    Mar 2015
    Posts
    184
    The way I learned was: follow video tutorials on youtube, try some exercises listed on a c++ site and play around with code. Refer to c++ books or google to solve any problems/questions encountered.

  5. #5
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Books are generally better since they cover more material in an organized manner.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  6. #6
    Registered User
    Join Date
    Mar 2015
    Posts
    384
    Quote Originally Posted by Elysia View Post
    You will have to show your code if we are to be able to figure out what's wrong. I can make a guess, though, and that's integer division. If the two operands you're trying to divide are both integers, then the result will also be an integer, so e.g. 2/3 = 0, not 0.6667. Make sure one of your operands are a float or double, or multiply one of them with 1.0 to ensure you get your decimals.

    For 6), it essentially boils down to sorting your input. There are built-in sorting methods in the standard library. Check cppreference.com.

    7) is essentially the same as 6), only with strings instead of integers. Yes, sorting works with strings, as well, so no problem there.

    8) How do we know if a number if odd or even in real life? Well, if it's divisable with 2, we know it's even. And if it's not even, then it's odd. How do we know a number if divisable by a certain number? We check that the remainder of the division. This can be done with the modulus operator.


    Not sure what your question is here. Can you clarify?

    Last but not least, if you have problems with exercises, post your code along with what exactly you're having trouble with. If the code does not compile, also post the compile errors.

    Oh, and I should mention that Jumping into C++ is bad book. I suggest you start with Accelerated C++ first.
    For the one where I also have to find the ratio, this is what I've got right now:

    Code:
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
        int val1, val2;
        cout << "Program to multiply and add, as well as find the smaller, larger, and the ratio of two integers\n";
        cout << "Note: For the sake of the ratio, please make sure that the second value is smaller than the first.\n";
        cout << "Please enter the first value: ";
        cin >> val1;
        cin.ignore();
        cout << "Please enter the second value: ";
        cin >> val2;
        cin.ignore();
    
        int larger_value = (val1 > val2) ? val1 : val2;
        cout << "The larger value is " << larger_value << ".\n";
    
        if (val2 > val1)
        {
            cout << val1 << " is smaller.\n";
        }
        else
        {
            cout << val2 << " is smaller.\n";
        }
    
        double ratio_value = val1 * 1.0 / val2 * 1.0;
        cout << "The ratio of the two values is: " << ratio_value << ".\n";
    
        int sum = val1 + val2;
        cout << "The sum of the two values is " << sum << ".\n";
        cin.ignore();
    }
    [it's not just ratios, as you can see: the exercise in the book asked to find the sum, ratio, larger, smaller, and product of the two numbers - I have them all right, I'm sure, with the exception of the ratio.]

    For the even/odd one, here is the code (I got that one to work - I just need help with getting to also work with floating-point values so that I can get exact answers for numbers where the decimal point is included):
    Code:
    #include <iostream>
    
    using namespace std;
    
    bool isDivisibleByTwo(long int input_value);
    
    int main()
    {
        cout << "Program For Checking if Input Number is Even or Odd\n";
        cout << "Please enter a number: ";
        long int input_value;
        cin >> input_value;
        cin.ignore();
        if (input_value == 0)
        {
            cout << "0 is not even or odd! Invalid input\n";
            return 1;
        }
        else if (isDivisibleByTwo(input_value))
        {
            cout << input_value << " is an even number.\n";
        }
        else
        {
            cout << input_value << " is an odd number.\n";
        }
        cin.ignore();
    }
    
    bool isDivisibleByTwo(long int input_value)
    {
        if (input_value % 2 != 0)
        {
            return false;
        }
        return true;
    }
    And here's what I have for the text to number conversion code:
    Code:
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
        string number_text;
        cout << "Program for converting numbers in text form to digits\n";
        cout << "Please enter a number in text form (any number from \"zero\" through \"four\"): ";
        cin >> number_text;
        cin.ignore();
        if (number_text == "stupid computer!")
        {
            cout << "I do not know that number, if it even is a number.\n";
            return 0;
        }
        else if (number_text == "zero")
        {
            cout << "Text converted to digit is 0\n";
        }
        else if (number_text == "one")
        {
            cout << "Text converted to digit is 1\n";
        }
        else if (number_text == "two")
        {
            cout << "Text converted to digit is 2\n";
        }
        else if (number_text == "three")
        {
            cout << "Text converted to digit is 3\n";
        }
        else if (number_text == "four")
        {
            cout << "Text converted to digit is 4\n";
        }
        cin.ignore();
    }
    The exercise in the book seems to be asking to only do it for the numbers 0 through 4, so I did it like that. I would've been able to do it like this for the numbers up until #12, but that's where I'd start having problems. I know I'd have to use if-statements and for-loops, but the way to construct the statements and code (for the if-statements, it's both, pretty much, but for the for-loops, it should just be the code within the curly-braces itself).

    The book also had readers write a mile-to-kilometer conversion program in the same chapter's review, so I also did that, but I do want to know if I could've gotten it to be more accurate - and if so, how.

    Here is the code:
    Code:
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
        double miles;
        cout << "\t-- Mile to Kilometer Conversion Program -- \n";
        cout << "Please enter distance in miles: ";
        cin >> miles;
        cin.ignore();
        double kilometers = miles / 0.62137;
        cout << "Your distance in kilometers is " << kilometers << "km.\n";
        cin.ignore();
    }

  7. #7
    Registered User
    Join Date
    Mar 2015
    Posts
    184
    according to wikipedia a mile is EXACTLY 1.609344km. So if you type in miles=1 in your program this number should be shown. Use cout.precision(7);

    refs:
    c++ - How do I print a double value with full precision using cout? - Stack Overflow
    https://en.wikipedia.org/wiki/Mile

  8. #8
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    >>if (val2 > val1)
    You've got "is smaller" duplicated in both if statements here. Besides, consider the case when val2 == val1.

    For the even/odd one, here is the code (I got that one to work - I just need help with getting to also work with floating-point values so that I can get exact answers for numbers where the decimal point is included):
    Consider the fact that in real life, only integers can be odd or even--not rational and irrational numbers, so it makes no sense.

    The exercise in the book seems to be asking to only do it for the numbers 0 through 4, so I did it like that. I would've been able to do it like this for the numbers up until #12, but that's where I'd start having problems. I know I'd have to use if-statements and for-loops, but the way to construct the statements and code (for the if-statements, it's both, pretty much, but for the for-loops, it should just be the code within the curly-braces itself).
    For this one, consider some pseudo code or a flow chart first. Remember that cin >> only reads up to a space, so it's easy to separate words by reading into a string via cin >>.

    The book also had readers write a mile-to-kilometer conversion program in the same chapter's review, so I also did that, but I do want to know if I could've gotten it to be more accurate - and if so, how.
    You could look at I/O manipulators to print out more decimals.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  9. #9
    Registered User
    Join Date
    Mar 2015
    Posts
    184
    "stupid computer" was just an example of garbage input your function should be able to handle...
    Also for bonus points try using a switch:
    Evaluate a string with a switch in C++ - Stack Overflow

  10. #10
    Registered User
    Join Date
    Mar 2015
    Posts
    384
    Quote Originally Posted by jiggunjer View Post
    "stupid computer" was just an example of garbage input your function should be able to handle...
    Also for bonus points try using a switch:
    Evaluate a string with a switch in C++ - Stack Overflow
    I know it's just an example, but I didn't know how to do it the right way.

    About the ratio problem, I really still don't get how to correctly output the ratio. I'm dividing the two values as decimal numbers now, but what else do I have to do? It can't really be that I just divide them, can it?

    The book just asks to convert text to numbers for 0 through 4, so I'll just leave it at that.

    @Elysia: Point noted (about rational and irrational numbers not being even or odd). I'll just leave that program as it is, then.

    As for the mile-to-kilometer converter, @jiggunger: Could you please tell me how to actually use cout.precision?

    Right now, when I run this code:
    Code:
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
        double miles;
        cout << "\t-- Mile to Kilometer Conversion Program -- \n";
        cout << "Please enter distance in miles: ";
        cin >> miles;
        cin.ignore();
        double kilometers = miles / 0.62137;
        cout.precision(7) << "Your distance in kilometers is " << kilometers << "km.\n";
        cin.ignore();
    }
    I get this error:
    Code:
    C:\Users\Osman\programming\stroustrup_programming_using_c++\mile_to_kilometer\mile_to_kilometer.cpp|13|error: invalid operands of types 'std :: streamsize {aka long long int}' and 'const char [32]' to binary 'operator<<'|
    I need to understand everything I can about this first, like how to use streamsizes.

    Edit: I don't know why, but the site is apparently somehow looking at the quote in this post as code.

    Edit2: Never mind about cout.precision() function, as I was able to at least get it to work; I just need to figure out how to output the correct, exact value for input of miles=1.

    This is my code now:
    Code:
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
        double miles;
        cout << "\t-- Mile to Kilometer Conversion Program -- \n";
        cout << "Please enter distance in miles: ";
        cin >> miles;
        cin.ignore();
        double kilometers = miles / 0.62137;
        cout.unsetf(ios::floatfield);
        cout.precision(7);
        cout << "Your distance in kilometers is " << kilometers << "km.\n";
        cin.ignore();
    }
    In the output, when I put in 1 for miles, I get 1.609347km. How do I get it to display 1.609344km?

    Edit3: I needed to write this as my assignment for double-type variable kilometers: kilometers = miles / 0.621371192237; I saw on another site that the number of kilometers in a mile is 0.621371192237. Now the output for miles=1 is "Your distance in kilometers is 1.609344km." which is what it should be. Yay!

    Now I just need to write that program for sorting out three input strings in ascending order.
    Last edited by Osman Zakir; 04-04-2015 at 05:15 PM.

  11. #11
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by Osman Zakir View Post
    I know it's just an example, but I didn't know how to do it the right way.
    How about you pick out the right values and reject the rest?

    About the ratio problem, I really still don't get how to correctly output the ratio. I'm dividing the two values as decimal numbers now, but what else do I have to do? It can't really be that I just divide them, can it?
    What else do you want? What is a ratio to you?

    In the output, when I put in 1 for miles, I get 1.609347km. How do I get it to display 1.609344km?
    Well, 1 divided by 0.62137 is 1,609347, so I'm guessing either the information is wrong or you're dividing by the wrong number.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  12. #12
    Registered User
    Join Date
    Mar 2015
    Posts
    384
    @Elysia: So I just need to divide it, for the ratio? How do I simplify the values as much as possible (if at all possible) and then display the ratio in number:number format? That's what I wanted to understand how to do.

    As for the miles-to-kilometers converter, I was able to get it to work (check 3rd Edit in previous post); here is the code:
    Code:
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
        double miles;
        cout << "\t-- Mile to Kilometer Conversion Program -- \n";
        cout << "Please enter distance in miles: ";
        cin >> miles;
        cin.ignore();
        double kilometers = miles / 0.621371192237;
        cout.unsetf(ios::floatfield);
        cout.precision(7);
        cout << "Your distance in kilometers is " << kilometers << "km.\n";
        cin.ignore();
    }
    I also got the number and string sorting programs to work, as desired, although since the former one's exercise was asking for integers, I had to fix that in my code as well.

    Now, one last exercise from this chapter that I need to ask about:

    11 Write a program that prompts the user to enter some number of pennies (1-cent coins), nickels (5-cent coins), dimes (10-cent coins), quarters (25-cent coins), half dollars (50-cent coins), and one-dollar coins (100-cent coins). Query the user separately for the number of each size coin, e.g., “How many pennies do you have?” Then your program should print out something like this:

    You have 23 pennies.
    You have 17 nickels.
    You have 14 dimes.
    You have 7 quarters.
    You have 3 half dollars.
    The value of all of your coins is 573 cents.



    Make some improvements: if only one of a coin is reported, make the output grammatically correct, e.g., 14 dimes and 1 dime (not 1 dimes). Also, report the sum in dollars and cents, i.e., $5.73 instead of 573 cents.
    I just need to get how to get it to correctly print out the amount of money in dollars and cents; I should be able to at least print it out in just cents. Is there a way write code that would automatically do it, or do I have to hard-code it (i.e. 573 cents is $5.73 because I know to put the decimal point right after the 5)?
    Last edited by Osman Zakir; 04-04-2015 at 05:49 PM.

  13. #13
    Registered User
    Join Date
    Mar 2015
    Posts
    184
    Well, 1 divided by 0.62137 is 1,609347, so I'm guessing either the information is wrong or you're dividing by the wrong number.
    1/0.62137 is 1.6093. 5 significant numbers limits precision.

  14. #14
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by Osman Zakir View Post
    @Elysia: So I just need to divide it, for the ratio? How do I simplify the values as much as possible (if at all possible) and then display the ratio in number:number format? That's what I wanted to understand how to do.
    Oh, I see. Well, I guess you should calculate the greatest common divisor by something like Euclid's algorithm then.

    I just need to get how to get it to correctly print out the amount of money in dollars and cents; I should be able to at least print it out in just cents. Is there a way write code that would automatically do it, or do I have to hard-code it (i.e. 573 cents is $5.73 because I know to put the decimal point right after the 5)?
    If I have xyz cents, how many dollars do I have?
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  15. #15
    Registered User
    Join Date
    Mar 2015
    Posts
    384
    Quote Originally Posted by Elysia View Post
    Oh, I see. Well, I guess you should calculate the greatest common divisor by something like Euclid's algorithm then.


    If I have xyz cents, how many dollars do I have?
    So would writing an if-condition to check (number_of_cents >= 100) be good? And if so, and I need a for-loop, how should I have it put the decimal points at the right spot?

    And is this good so far?
    Code:
    #include <iostream>
    
    using namespace std;
    
    int moneyCount(int pennies, int dimes, int nickels, int quarters, int half_dollars, int dollar_coins);
    
    int main()
    {
        int pennies, dimes, nickels, quarters, half_dollars, dollar_coins;
        cout << "Program to count amount of money in dollars and cents\n";
        cout << "Please specify how many of each you have;\n";
        cout << "pennies: ";
        cin >> pennies;
        cin.ignore();
        cout << "dimes: ";
        cin >> dimes;
        cin.ignore();
        cout << "nickels: ";
        cin >> nickels;
        cin.ignore();
        cout << "quarters: ";
        cin >> quarters;
        cin.ignore();
        cout << "half_dollars: ";
        cin >> half_dollars;
        cin.ignore();
        cout << "dollar_coins: ";
        cin >> dollar_coins;
        cin.ignore();
        money(pennies, dimes, nickels, quarters, half_dollars, dollar_coins);
    }
    
    int moneyCount(int pennies, int dimes, int nickels, int quarters, int half_dollars, int dollar_coins)
    {
        if (pennies > 1)
        {
            cout << "You have " << pennies << " pennies.\n";
        }
        else if (pennies == 1)
        {
            cout << "You have 1 penny.\n";
        }
        
        if (dimes > 1)
        {
            cout << "You have " << dimes << " dimes.\n";
        }
        else if (dimes == 1)
        {
            cout << 
        }
    }
    Or should I wrap the '1' in quotes (if so, then single or double?)?

    And is the approach good so far, or am I messing up in a huge way here?

    By the way, anybody of a good, free, Web-based VPN service? Or just a good way to configure OpenVPN with a free account so that I can use my credentials and successfully connect to it?

    Edit: How should I calculate the number of coins, though? I mean, like, how do I make the program correctly calculate the values of the coins and add them such that it prints out the correct value in dollars and cents?
    Last edited by Osman Zakir; 04-05-2015 at 06:21 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Getting user input for structure variables
    By themolejoel in forum C Programming
    Replies: 7
    Last Post: 10-17-2011, 10:49 PM
  2. finding user permissions
    By aadil7 in forum C Programming
    Replies: 3
    Last Post: 03-17-2011, 10:02 AM
  3. user input type variables
    By pastitprogram in forum C++ Programming
    Replies: 1
    Last Post: 09-05-2008, 07:21 AM
  4. Finding User names.....
    By twomers in forum C++ Programming
    Replies: 2
    Last Post: 12-05-2005, 04:46 AM
  5. Finding user and group IDs
    By halfbreed in forum C Programming
    Replies: 10
    Last Post: 05-10-2004, 06:29 PM