Thread: Finding Ratio of Two Variables Input by User

  1. #16
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by Osman Zakir View Post
    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?
    No, think about it: if I gave you 123 cents, how many dollars would you have? How would you calculate it?

    And is this good so far?
    Looks good for an initial attempt.

    Or should I wrap the '1' in quotes (if so, then single or double?)?
    Quotes are for characters. '1' means the character 1, not the number 1. Double quotes are for (C-style) strings, which is just an array of characters with a \0 at the end, so "1" is just '1' and '\0'. Since your money is of integral type, you should compare with...?

    And is the approach good so far, or am I messing up in a huge way here?
    The approach is good so far. It can be simplified later perhaps, due to repetition of much code, but that's for later.

    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?
    Probably should just ask this separately in the techtalk forum.

    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?
    How would you do it in real life? Pick an example (that is, make up some number of each coin) and write it down in simple steps how you do it.
    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.

  2. #17
    Registered User
    Join Date
    Mar 2015
    Posts
    384
    Let's see; so if I have $6.00, that's the same as 600 pennies. If I split those up into at least one of each kind of coin . . .

    I could have 3 100-cent coins, 4 half-dollar coins, 2 quarters, 10 pennies, 2 nickels, 3 dimes, which have the value 600 cents, meaning 6 dollars. How do I tell the computer that?

    If you gave me 123 cents, that'd mean you gave me $1.23, and it could be 4 quarters, 2 dimes and 3 pennies, it could be one 1-dollar coin, 2 dimes, and 3 pennies; there are a number of possible combinations. But, again, I don't know yet how to tell the computer that.

    As for my current code, if I'm on the right track so far on that, then once I've told the program how many cents the user has, the next step would be figuring out how code in the right value of the coins and compute the amount of money reported. Right?

  3. #18
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Well, I don't see anywhere in the exercise that you should only input cents and converts that to the different coins. I only see that you should enter the different coin amounts, convert it to cents and dollars.

    >>If you gave me 123 cents, that'd mean you gave me $1.23
    So how did you get $1.23?

    So for the reverse, think about this: if a product cost $0.99 and you pay $2, how do you figure out how much exchange to give back, and how many of each coin?
    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. #19
    Registered User
    Join Date
    Mar 2015
    Posts
    384
    Another program I had to write for this chapter was a calculator program; I wrote it, and it was working just fine, but then I decided to include an option to continue or not in main, with a while-loop that would end once the user entered 'Q' or 'q' for the prompt "Continue (C == Continue, Q == Quit)?", but it isn't working correctly in that part of the code. It takes the answer, but then it doesn't go into the loop.

    Here is the code:
    Code:
    #include <iostream>
    
    using namespace std;
    
    double calculator(string operation, double first_value, double second_value);
    
    int main()
    {
        cout << "< -- Mini Calculator Program -- >\n";
        cout << "Please provide operation (+, -, /, *): ";
        string operation;
        cin >> operation;
        cin.ignore();
        double first_value;
        double second_value;
        cout << "Please enter the first value: ";
        cin >> first_value;
        cin.ignore();
        cout << "Please enter the second value: ";
        cin >> second_value;
        cin.ignore();
        double result = calculator(operation, first_value, second_value);
        cout << "The result of your calculation is: " << result << ".\n";
        cout << "Would you like to continue?\n";
        char answer;
        cin >> answer;
        if (answer == 'Y' || answer == 'y')
        {
            char continuation;
            while (continuation == 'C' || continuation == 'c')
            {
                calculator(operation, first_value, second_value);
                cout << "Continue (C == Continue, Q == Quit)?\n";
                cin >> continuation;
                cin.ignore();
                if (continuation == 'Q' || continuation == 'q')
                {
                    cout << "Alright, thanks for using this calculator program.\nQuitting . . . \n";
                    return 0;
                }
            }
        }
        else
        {
            cout << "Alright, thanks for using this calculator program.\nQuitting . . . \n";
            return 0;
        }
        cin.ignore();
    }
    
    double calculator(string operation, double first_value, double second_value)
    {
        double result;
        if (operation == "+")
        {
            result = first_value + second_value;
        }
        else if (operation == "-")
        {
            result = first_value - second_value;
        }
        else if (operation == "/")
        {
            result = first_value / second_value;
        }
        else if (operation == "*")
        {
            result = first_value * second_value;
        }
        return result;
    }
    And I also got the coin program to work. Just let me know of a way to make it more efficient and simple, if there's a way to do that.
    Code:
    #include <iostream>
    
    using namespace std;
    
    double 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();
        double money_value = moneyCount(pennies, dimes, nickels, quarters, half_dollars, dollar_coins);
        cout << "You have $" << money_value << ".\n";
    }
    
    double 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 << "You have 1 dime.\n";
        }
    
        if (nickels > 1)
        {
            cout << "You have " << nickels << " nickels.\n";
        }
        else if (nickels == 1)
        {
            cout << "You have 1 nickel.\n";
        }
    
        if (quarters > 1)
        {
            cout << "You have " << quarters << " quarters.\n";
        }
        else if (quarters == 1)
        {
            cout << "You have 1 quarter.\n";
        }
    
        if (half_dollars > 1)
        {
            cout << "You have " << half_dollars << " half dollars.\n";
        }
        else if (half_dollars == 1)
        {
            cout << "You have 1 half dollar.\n";
        }
    
        if (dollar_coins > 1)
        {
            cout << "You have " << dollar_coins << " dollar coins.\n";
        }
        else if (dollar_coins == 1)
        {
            cout << "You have 1 dollar coin.\n";
        }
    
        int penny_value = pennies * 1, nickel_value = nickels * 5, dime_value = dimes * 10, quarter_value = quarters * 25;
        int half_dollar_value = half_dollars * 50, dollar_value = dollar_coins * 100;
        int total_coins = penny_value + nickel_value + dime_value + quarter_value + half_dollar_value + dollar_value;
        double money_amount = total_coins * 1.0 / 100;
        return money_amount;
    }
    Any help with either one or both would be much appreciated. Thanks in advance.

  5. #20
    Registered User
    Join Date
    Mar 2015
    Posts
    184
    Code:
    #include <iostream>
    #include <string>
    
    
    using std::cout;
    using std::endl;
    
    
    void doublecastfcn(int arr[6])
    {
      double farr[6] {};
      for (int i=0;i<6;i++)
        farr[i] = arr[i]; //implicit cast
      cout<<"money is: ";
      cout<<(farr[0]*1+farr[1]*5+farr[2]*10+farr[3]*25+farr[4]*50+farr[5]*100) / 100;
      cout<<" dollarz/euroz/yenz/poundz"<<endl;
    }
    
    
    int main()
    {
      std::string plural[6] {"pennies","dimes","nickels","quarters","halfs","dollars"};
      std::string singular[6] {"penny","dime","nickel","quarter","half","dollar"};
      int arr[6] {1,2,3,4,5,6}; //user input goes into array, no need to spam cin.ignore()...
    
    
      //print it:
      for (int i=0;i<6;i++)
      {
        cout<<"You have "<<arr[i]<<" ";
        if (arr[i]>1){cout<<plural[i]<<endl;}
        else{cout<<singular[i]<<endl;}
      }
    
    
      doublecastfcn(arr); //calculate money
    }

  6. #21
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    The exercise is specifically about asking the user for input, not encoding it into an array. Besides, this array approach, while more compact, reduces readability.
    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.

  7. #22
    Registered User
    Join Date
    Mar 2015
    Posts
    184
    So? he can modify it to fill the array elements with user input? To me my version is more readable and easier to maintain/scale. It demonstrates casting instead of multiplying with a hardcoded number. It also shows how loops can reduce patterns in code. Educational I hoped.

  8. #23
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Educational it certainly is. But what index of the array is nickels? Dimes? Pennies? Hard to know. Hard to read.
    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. #24
    Registered User
    Join Date
    Mar 2015
    Posts
    384
    ^Exactly. I do want to know of a good looping technique I can use where I don't have to hard-code it so much, but really, I'd like to be able to read the code and know what variable is for which type of coin and which value is being given to which coin.

    It certainly would be good if I could make it more simple and efficient. Stroustrup keeps repeating in his book that code should be correct, simple, and efficient (the importance of each is seen by the order in which they each are listed, by the way, so correctness is most important -- he also said that it doesn't matter if a program is really fast if its output is incorrect, and also that code shouldn't be complicated). If the program's execution time could be reduced, that'd be great.

    Edit: About that calculator program I mentioned; it'd still be good if somebody help me make it more simple and efficient, but for now I've at least got the loop to work:
    Code:
    #include <iostream>
    
    using namespace std;
    
    double calculator(string operation, double first_value, double second_value);
    
    int main()
    {
        char answer;
        cout << "< -- Mini Calculator Program -- >\n";
        cout << "Please provide operation (+, -, /, *): ";
        string operation;
        cin >> operation;
        cin.ignore();
        double first_value;
        double second_value;
        cout << "Please enter the first value: ";
        cin >> first_value;
        cin.ignore();
        cout << "Please enter the second value: ";
        cin >> second_value;
        cin.ignore();
        double result = calculator(operation, first_value, second_value);
        cout << "The result of your calculation is: " << result << ".\n";
        cout << "Would you like to continue (Y/N)?\n";
        cin >> answer;
        cin.ignore();
        if (answer == 'Y' || answer == 'y')
        {
            while (answer == 'Y' || answer == 'y')
            {
                cout << "Please provide operation (+, -, /, *): ";
                cin >> operation;
                cin.ignore();
                cout << "Please enter the first value: ";
                cin >> first_value;
                cin.ignore();
                cout << "Please enter the second value: ";
                cin >> second_value;
                cin.ignore();
                result = calculator(operation, first_value, second_value);
                cout << "The result of your calculation is: " << result << ".\n";
                cout << "Would you like to continue (Y/N)?\n";
                cin >> answer;
                cin.ignore();
                if (answer == 'N' || answer == 'n')
                {
                    cout << "Very well. Thanks for using this calculator program.\nQuitting . . . \n";
                    return 0;
                }
            }
        }
        else if (answer == 'N' || answer == 'n')
        {
            cout << "Very well. Thanks for using this calculator program.\nQuitting . . . \n";
            return 0;
        }
        else
        {
            cout << "That's not Y or N!\n";
            return 0;
        }
        cin.ignore();
    }
    
    double calculator(string operation, double first_value, double second_value)
    {
        double result;
        if (operation == "+")
        {
            result = first_value + second_value;
        }
        else if (operation == "-")
        {
            result = first_value - second_value;
        }
        else if (operation == "/")
        {
            result = first_value / second_value;
        }
        else if (operation == "*")
        {
            result = first_value * second_value;
        }
        return result;
    }
    Last edited by Osman Zakir; 04-06-2015 at 04:54 PM.

  10. #25
    Registered User
    Join Date
    Mar 2015
    Posts
    184
    What if you had 20 currency units instead of 5? want 20 variables and 4 screens of text to wade through to find a typo or debug other things?

    Plus if you're smart with design it doesn't matter that you know which variable corresponds to which coin. You can do a loop for getting input using both the string array and the integer array. That way the output is always linked to the input, even if you change the order of dimes/nickels etc. You don't even need to read the string array. Though you'd have to modify calculate money slightly to cope with the flexibility.

    As for your calculator, again you have code repetition, so try to only use the loop. I actually did this exercise I think, long time ago. Here's the code I had back then:

    Code:
    #include <iostream>
    #include <string>
    #include <cctype>
    #include <cstdlib> //atoi, because std::stoi isn't an option :-), same goes for atof
    #include <sstream> //for custom stoi function, std::stoi doesn't work with windows g++
    #include <limits> //numeric_limits for flushing cin buffer
    
    
    using std::cout;
    using std::endl;
    using std::cin;
    
    
    float multiply(float x, float y)
    {    return x*y;}
    float divide(float x, float y)
    {    return x/y;}
    float add(float x, float y)
    {    return x+y;}
    float subtract(float x, float y)
    {    return x-y;}
    
    
    int stoi(const std::string& s) { //deprecated, using floats now
        std::istringstream str(s);
        int i;
        str >> i;
        return i;
    }
    
    
    float stof(const std::string& s) {
        std::istringstream str(s);
        float i;
        str >> i;
        return i;
    }
    
    
    bool nondigit(const std::string& s) //true if s contains a non-digit other than a single '.' or starting '-'
    {
      bool b = false;
      int dotcnt = 0; //for floats
      int i = 0;
      auto msg = [&]() { cout<<"!!"<<s[i]<<"!!\n"<<"Invalid number, retry please"<<endl; };
    
    
      for (i;i<s.length();i++)
      {
        if (std::isdigit(s[i])) {/*keep going*/}
        else if (s[i]=='.') {
            if(dotcnt==0){++dotcnt;}
            else{msg(); b = true; break;}
        }
        else if (s[i]=='-'){
          if(i>0){msg(); b = true; break;}//minus not at front: exit
        }
        else {msg(); b=true; break;}
      }
      return b;
    }
    
    
    
    
    void getinput(float &x, float &y) //parses getlines
    {
        std::string xstr;
        std::string ystr;
        cout<<"Enter x (left operand)"<<endl;
    
    
        do{
        getline(cin,xstr);
        }while ((xstr.length()==0) || (nondigit(xstr)));
    
    
        x = stof(xstr); //version 1
        cout<<"Enter y (right operand)"<<endl;
    
    
        do{
        getline(cin,ystr);
        }while((ystr.length()==0) || (nondigit(ystr)));
    
    
        y = atof(ystr.c_str()); //version 2
    }
    
    
    void promptuser(char &op) //cin<< char with input checking
    {
        cout<<"What operation would you like to perform?: add(+),subtract(-), divide(/), multiply(*), exit(e)";
        do
        {
          cin.get(op);
          if (cin.fail())
          {
          cout<<"How'd you break it?"<<endl;
          cin.clear();
          }
        cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        if ((op=='e')||(op=='+')||(op=='-')||(op=='*')||(op=='/')){break;}
        else {cout<<"Wrong input, try again (case sensitive)"<<endl;}
        }while(true);
    }
    
    
    
    
    int main()
    {
    char op {}; //operator input
    float x,y;
    
    
        while(op!='e')
        {
        promptuser(op);
        if (op!='e')
        {
            getinput(x,y);
            switch(op)
            {
            case '+':
             cout<<x<<"+"<<y<<"="<<add(x,y)<<endl;         break;
            case '-':
             cout<<x<<"-"<<y<<"="<<subtract(x, y)<<endl;         break;
            case '/':
             cout<<x<<"/"<<y<<"="<<divide(x, y)<<endl;         break;
            case '*':
             cout<<x<<"*"<<y<<"="<<multiply(x, y)<<endl;         break;
             default: throw "somehow you managed to enter something weird for op";
            }
        }
        else
        {
            cout<<"Shutting down...";
        }
        }
    
    
    
    
        return 0;
    }
    Last edited by jiggunjer; 04-06-2015 at 11:06 PM.

  11. #26
    Registered User
    Join Date
    Mar 2015
    Posts
    384
    Well, for the calculator, how does this look?
    Code:
    #include <iostream>
    
    using namespace std;
    
    double calculator(string operation, double first_value, double second_value);
    
    int main()
    {
        char answer;
        cout << "< -- Mini Calculator Program -- >\n";
        do
        {
            cout << "Please provide operation (+, -, /, *): ";
            string operation;
            cin >> operation;
            cin.ignore();
            double first_value;
            double second_value;
            cout << "Please enter the first value: ";
            cin >> first_value;
            cin.ignore();
            cout << "Please enter the second value: ";
            cin >> second_value;
            cin.ignore();
            double result = calculator(operation, first_value, second_value);
            cout << "The result of your calculation is: " << result << ".\n";
            cout << "Would you like to continue (Y/N)?\n";
            cin >> answer;
            cin.ignore();
            if (answer == 'N' || answer == 'n')
            {
                cout << "Very well.  Thank you for using this calculator program.\n";
                break;
            }
            else
            {
                continue;
            }
        } while (answer == 'Y' || answer == 'y');
        cin.ignore();
    }
    
    double calculator(string operation, double first_value, double second_value)
    {
        double result;
        if (operation == "+")
        {
            result = first_value + second_value;
        }
        else if (operation == "-")
        {
            result = first_value - second_value;
        }
        else if (operation == "/")
        {
            result = first_value / second_value;
        }
        else if (operation == "*")
        {
            result = first_value * second_value;
        }
        return result;
    }
    Is that better? I was able to make it so that the user gets to make more calculations if he/she wants to. And it's in a do-while loop, like your old one (haha).

    Also, how would you convert a number as text to digits (please don't just give me the answer - let me work through it).

  12. #27
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    How would you write them in real life? If I gave you 123, how'd you write it with words?
    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.

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